列组和计数

时间:2013-11-06 01:49:05

标签: sql grouping

是否可以使用下表创建查询:

    YEAR    MAKE    MODEL
    2012    CHEVY   CAMARO
    2012    CHEVY   CORVETTE
    2013    CHEVY   CORVETTE
    2013    CHEVY   CAMARO
    2013    NISSAN  GT-R

将输出如下结果:

    CATEGORY    VALUE    TOTAL
    YEAR        2012     2
    YEAR        2013     3
    MAKE        CHEVY    4
    MAKE        NISSAN   1
    MODEL       CAMARO   2
    MODEL       CORVETTE 2
    MODEL       GT-R     1

1 个答案:

答案 0 :(得分:1)

SELECT 'YEAR' AS category, CAST(year AS VARCHAR(4)), COUNT(*) AS total FROM YouTable
GROUP BY year
UNION ALL
SELECT 'MAKE' AS category, make, COUNT(*) FROM YouTable
GROUP BY make
UNION ALL
SELECT 'MODEL' AS category, model, COUNT(*) FROM YouTable
GROUP BY model

SQL标准查询,如果您的RDBMS是SQL SERVER版本> = 2005或Oracle版本> = 10g 你可以使用PIVOT / UNPIVOT CLAUSE。