如何在SQL中基于int min()函数选择varchar列

时间:2015-01-03 09:21:30

标签: sql sql-server visual-studio

我想分别为每个tid选择具有最小twu值的项目...我的表名重组了

tid items      times twu
1   A           7   942
1   D           5   633
1   H           2   1020
2   S           4   551
3   F           4   871
3   B           2   641
4   M           1   665
4   N           7   950
4   Z           10  986
5   B           6   641
5   C           8   370
5   D           1   633
6   J           6   842
6   K           2   397
6   L           5   305

我试过这段代码

select tid,items,twu from REORGANISED where (TID,twu) in 
(select TID,min(twu)as TWU from REORGANISED group by tid);

在条件

中显示出一些错误

4 个答案:

答案 0 :(得分:2)

您可以通过加入现有子查询和原始表本身来获得所需的结果。此解决方案适用于所有rdbms。

SELECT  a.*
FROM    Reorganised a
        INNER JOIN
        (
            select TID,min(twu)as TWU 
            from REORGANISED 
            group by tid
        ) b ON  a.TID = b.TID
                AND a.TWU = b.TWU

答案 1 :(得分:0)

WITH CTE AS (
SELECT tid,items,times,twu,
ROW_NUMBER() OVER (PARTITION BY tid ORDER BY twu DESC) rn
FROM REORGANISED 
)
SELECT * FROM CTE WHERE rn=1

答案 2 :(得分:0)

row_number函数应该可以解决问题:

SELECT tid, items, times, twu
FROM   (SELECT tid, items, times, twu, 
               ROW_NUMBER() OVER (PARTITION BY tid ORDER BY twu DESC) AS rn
        FROM   reorganised) y
WHERE  rn = 1

答案 3 :(得分:0)

SELECT  a.TID,ITEMS
FROM    Reorganised a
        INNER JOIN
        (
            select TID,min(twu)as TWU 
            from REORGANISED 
            group by tid
        ) b ON  a.TID = b.TID
                AND a.TWU = b.TWU