格式化SQL查询以不同方式显示

时间:2012-06-10 23:16:32

标签: sql sql-server tsql

我是编写查询的初学者,并且一直绞尽脑汁试图弄清楚最好的方法是什么。我创建了一个临时表并编写了一个查询,以便从以下数据中获得以下数据:

SELECT Temp.OrderType,Temp.OrderDate,COUNT(*) as prodCount
FROM Temp
GROUP BY Temp.OrderType, Temp.OrderDate
ORDER BY Temp.OrderType;

结果

OrderType    OrderDate                  prodCount
1            2012-06-04 00:00:00.000    1
1            2012-06-06 00:00:00.000    1
2            2012-06-07 00:00:00.000    2
3            2012-06-05 00:00:00.000    1
3            2012-06-06 00:00:00.000    2
3            2012-06-07 00:00:00.000    1
7            2012-06-05 00:00:00.000    1
11           2012-06-07 00:00:00.000    1

如何以这种格式显示数据,而不是使用日期下的计数总数? Date1 Date2等,分别是6 / 04,6 / 06,6 / 06,6 / 07。任何帮助或指导表示赞赏。谢谢你!

OrderType Date1 Date2 Date3 Date4
1            1                1
2                             2
3                1      2     1
4
7                1
11                      1

示例数据

OrderDate                  OrderType
2012-06-06 00:00:00.000    1
2012-06-04 00:00:00.000    1
2012-06-05 00:00:00.000    7
2012-06-05 00:00:00.000    3
2012-06-06 00:00:00.000    3
2012-06-06 00:00:00.000    3
2012-06-07 00:00:00.000    3
2012-06-07 00:00:00.000    2
2012-06-07 00:00:00.000    2
2012-06-07 00:00:00.000    3
2012-06-07 00:00:00.000    11

2 个答案:

答案 0 :(得分:1)

如果你的数据库引擎是MSSQL,试试这个:

SELECT OrderDate, 
OrderType_1 = SUM(CASE OrderType WHEN 1 THEN 1 ELSE 0 END),
OrderType_2 = SUM(CASE OrderType WHEN 2 THEN 1 ELSE 0 END ),
OrderType_3 = SUM(CASE OrderType WHEN 3 THEN 1 ELSE 0 END),
OrderType_4 = SUM(CASE OrderType WHEN 4 THEN 1 ELSE 0 END),
OrderType_7 = SUM(CASE OrderType WHEN 7 THEN 1 ELSE 0 END),
OrderType_11= SUM(CASE OrderType WHEN 11 THEN 1 ELSE 0 END)
FROM Temp
GROUP BY OrderDate
ORDER BY OrderDate

答案 1 :(得分:1)

请试试这个

   DECLARE @sql varchar(4000)

    SET @sql =
        '
        SELECT  * 
        FROM    
        (
            SELECT OrderType,CONVERT(VARCHAR(10),OrderDate,112) AS OrderDate,prodCount 
            FROm t 
        )  st
        PIVOT 
        (
        SUM(prodCount)
        FOR OrderDate IN ( '
        +  
        STUFF(
            (
             SELECT ',['  + OrderDate + ']'
             FROM 
                (SELECT distinct CONVERT(VARCHAR(10),OrderDate,112) AS OrderDate  FROM t)  a
             FOR XML PATH('')
             ),1,1,'')
        + ')
        ) as pvt
        ORDER BY pvt.OrderType
        '

    PRINT @sql
    EXEC(@sql)

SQLFiddle link