Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 获取最小值(id)和相应的其他字段以及原始字段_Sql_Sql Server - Fatal编程技术网

Sql 获取最小值(id)和相应的其他字段以及原始字段

Sql 获取最小值(id)和相应的其他字段以及原始字段,sql,sql-server,Sql,Sql Server,我有一个表e ms sql,它有下面的结构和数据- +----+-------+-------+-------+-------+ | Id | colx | coly | colz | cola | +----+-------+-------+-------+-------+ | 1 | x1 | y1 | z1 | a | | 2 | x2 | y2 | y2 | a | | 3 | x3 | y3 | z3

我有一个表e ms sql,它有下面的结构和数据-

+----+-------+-------+-------+-------+
| Id |  colx |  coly |  colz |  cola |
+----+-------+-------+-------+-------+
|  1 | x1    | y1    | z1    | a     |
|  2 | x2    | y2    | y2    | a     |
|  3 | x3    | y3    | z3    | a     |
|  4 | x4    | y4    | y4    | a     |
|  5 | x5    | y5    | z5    | b     |
|  6 | x6    | y6    | z6    | b     |
+----+-------+-------+-------+-------+
我想要cola=a的select查询结果,其中colx和id应该来自cola=a和coly=colz的组的minid。。。。结果-

+------+---------+---------+---------+---------+
| RsId |  rscolx |  rscoly |  rscolz |  rscola |
+------+---------+---------+---------+---------+
|    2 | x2      | y1      | z1      | a       |
|    2 | x2      | y2      | y2      | a       |
|    2 | x2      | y3      | z3      | a       |
|    2 | x2      | y4      | y4      | a       |
+------+---------+---------+---------+---------+

您可以使用窗口函数。以下使用两个步骤:

这是我的sql还是MSSQL?
select t.*,
       min(case when id = min_id then colx end) over (partition by cola)
from (select t.*,
             min(case when coly = colz then id end) over (partition by cola) as min_id
      from t
      where cola = 'a'
     ) t;