T-SQL:根据列中的顶部值返回可变数量的记录

时间:2012-03-13 20:23:14

标签: sql tsql

如果我有桌子:

+------------------------------------------------------------+
|  Col 1                                     Col 2    Col 3  |
+------------------------------------------------------------+
|  a72195fa-57ca-4849-b423-5595219c8f6b      Val1     1      |
|  a72195fa-57ca-4849-b423-5595219c8f6b      Val2     1      |
|  a72195fa-57ca-4849-b423-5595219c8f6b      Val3     2      |
|  a72195fa-57ca-4849-b423-5595219c8f6b      Val4     3      |
|  2F6D0B9E-2221-4D18-A64E-ACCFB83EACC7      Val5     2      |
|  2F6D0B9E-2221-4D18-A64E-ACCFB83EACC7      Val6     2      |
|  2F6D0B9E-2221-4D18-A64E-ACCFB83EACC7      Val7     3      |
+------------------------------------------------------------+

对于给定的Col 1值,如何返回Col3中最小值的所有记录。含义[Col 1] = a72195fa-57ca-4849-b423-5595219c8f6b,我想返回:

+------------------------------------------------------------+
|  Col 1                                     Col 2    Col 3  |
+------------------------------------------------------------+
|  a72195fa-57ca-4849-b423-5595219c8f6b      Val1     1      |
|  a72195fa-57ca-4849-b423-5595219c8f6b      Val2     1      |
+------------------------------------------------------------+

[Col 1] = 2F6D0B9E-2221-4D18-A64E-ACCFB83EACC7我要返回的地方:

+---------------------------------------------------------+
| Col 1                                   Col 2    Col 3  |
+---------------------------------------------------------+
| 2F6D0B9E-2221-4D18-A64E-ACCFB83EACC7    Val5     2      |
| 2F6D0B9E-2221-4D18-A64E-ACCFB83EACC7    Val6     2      |
+---------------------------------------------------------+

4 个答案:

答案 0 :(得分:2)

SELECT A.*
FROM TABLE A,
(
SELECT Col1,MIN(Col3) AS Col3
FROM TABLE
GROUP BY Col1
) B
WHERE A.Col3=B.Col3;

答案 1 :(得分:2)

有点聪明(我认为):

SELECT * INTO #TEMP
FROM
(
 SELECT 'a72195fa-57ca-4849-b423-5595219c8f6b' col1, 'Val1' col2, 1 col3
UNION SELECT 'a72195fa-57ca-4849-b423-5595219c8f6b' col1, 'Val2' col2, 1 col3
UNION SELECT 'a72195fa-57ca-4849-b423-5595219c8f6b' col1, 'Val3' col2, 2 col3
UNION SELECT 'a72195fa-57ca-4849-b423-5595219c8f6b' col1, 'Val4' col2, 3 col3
UNION SELECT '2F6D0B9E-2221-4D18-A64E-ACCFB83EACC7' col1, 'Val5' col2, 2 col3
UNION SELECT '2F6D0B9E-2221-4D18-A64E-ACCFB83EACC7' col1, 'Val6' col2, 2 col3
UNION SELECT '2F6D0B9E-2221-4D18-A64E-ACCFB83EACC7' col1, 'Val7' col2, 3 col3
) A

SELECT * FROM #TEMP

SELECT *
FROM
(
 SELECT *
 , RANK() OVER(PARTITION BY col1 ORDER BY col3 ASC) _RANK
 FROM #TEMP
) a
WHERE a._RANK = 1

答案 2 :(得分:1)

以下是使用子查询的一种方法:

SELECT *
FROM myTable
WHERE Col3 = (SELECT MIN(Col3) FROM myTable WHERE Col1 = @SomePassedInGuid)
AND Col1 = @SomePassedInGuid

答案 3 :(得分:0)

这里基本上是李给出的相同查询,表达得更为紧凑。

select top (1) with ties
  Col1, Col2, Col3
from T
order by rank() over (
  partition by Col1
  order by Col3
)