2

我是编写查询的初学者,并且一直在绞尽脑汁试图找出最好的方法是什么。我创建了一个临时表并编写了一个查询来为我提供以下数据这个来自以下数据的结果。

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/05、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
4

2 回答 2

1

If your DB engine is MSSQL, try this:

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
于 2012-06-11T00:48:27.347 回答
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 链接

于 2012-06-11T16:17:25.453 回答