将多个嵌套的SELECT语句转换为PIVOT表

时间:2016-07-07 17:55:21

标签: sql-server pivot

我希望水平显示我的记录(Rows to Columns)并创建了以下用于完成工作的SQL语句,但我认为它可以更好。

我研究过PIVOT Tables并相信它们会让它变得更清洁/有效,我只是无法使PIVOT正常工作。欢迎所有建议:

SELECT  (SELECT
                COUNT(*)
            FROM ImportItem
            WHERE BodyTypeID = 1)
        AS [Sedan]
        ,(SELECT
                COUNT(*)
            FROM ImportItem
            WHERE BodyTypeID = 2)
        AS [Sport utility]
        ,(SELECT
                COUNT(*)
            FROM ImportItem
            WHERE BodyTypeID = 3)
        AS [Sport coupe]
        ,(SELECT
                COUNT(*)
            FROM ImportItem
            WHERE BodyTypeID = 4)
        AS [Station wagon]
        ,(SELECT
                COUNT(*)
            FROM ImportItem
            WHERE BodyTypeID = 5)
        AS [Convertible]
        ,(SELECT
                COUNT(*)
            FROM ImportItem
            WHERE BodyTypeID = 6)

        AS [Coupe]
        ,(SELECT
                COUNT(*)
            FROM ImportItem
            WHERE BodyTypeID = 7)

        AS [Roadster]
        ,(SELECT
                COUNT(*)
            FROM ImportItem
            WHERE BodyTypeID = 8)

        AS [Mini van]
        ,(SELECT
                COUNT(*)
            FROM ImportItem
            WHERE BodyTypeID = 9)
        AS [Pick-up]
        ,(SELECT
                COUNT(*)
            FROM ImportItem
            WHERE BodyTypeID = 10)
        AS [Hatchback]
        ,(SELECT
                COUNT(*)
            FROM ImportItem
            WHERE BodyTypeID = 11)
        AS [Cargo van]

由于

1 个答案:

答案 0 :(得分:1)

SELECT  COUNT(CASE WHEN BodyTypeID = 1 THEN 1 END) AS [Sedan],
        COUNT(CASE WHEN BodyTypeID = 2 THEN 1 END) AS [Sport utility],
        COUNT(CASE WHEN BodyTypeID = 3 THEN 1 END) AS [Sport coupe],
        etc..
FROM    ImportItem

SELECT  [1] AS [Sedan],
        [2] AS [Sport utility],
        [3] AS [Sport coupe],
        ect..
FROM    (SELECT BodyTypeID FROM ImportItem) t
PIVOT   (COUNT(BodyTypeID) FOR BodyTypeID IN ([1],[2],[3],etc..)) p