GROUP BY订购

时间:2012-10-11 23:35:15

标签: mysql sql

SELECT * FROM title给出了以下输出:

title_number    version_type    hd_sd
1000046         Standard    SD
1000046         Standard    HD
1000050         Standard    SD
1000093         Standard    SD
1000093         Standard    HD
1000125         Standard    SD
1000269         Standard    SD

我需要获取所有不同的title_numbers,然后hd_sd将= HD如果存在,否则它将= SD。正确的输出是:

title_number    version_type    hd_sd
1000046         Standard    HD
1000050         Standard    SD
1000093         Standard    HD
1000125         Standard    SD
1000269         Standard    SD

我最接近的是SELECT * FROM title GROUP BY title_number,但这并没有给我正确的hd_sd列值。我如何正确地进行此查询?

1 个答案:

答案 0 :(得分:2)

SELECT title_NUMBer, Version_type,
        MIN(hd_sd)
FROM tableName
GROUP BY title_NUMBer

进行改进,

SELECT a.*
FROM    tableName a
        INNER JOIN
        (
            SELECT title_NUMBer, MIN(hd_sd) minCol
            FROM tableName
            GROUP BY title_NUMBer
        ) b ON a.title_number = b.title_Number AND
                a.hd_sd = b.mincol