具有多列的枢轴

时间:2015-12-07 18:52:39

标签: sql-server

我正在努力在交易数据表上产生一个支点。我的数据表如下:

+------------+------------+-----------+------------+
|Date        |Store       |Customer   |Value       |
+------------+------------+-----------+------------+
|01/12/15    |StoreA      |Cust1      |3.80        |
|01/12/15    |StoreB      |Cust2      |2.40        |
|01/12/15    |StoreC      |Cust1      |3.80        |
|02/12/15    |StoreC      |Cust2      |1.50        |
|02/12/15    |StoreA      |Cust2      |1.50        |
|02/12/15    |StoreA      |Cust2      |2.00        |

我想从枢轴中获得的结果如下:

+-------+-----------+--------+--------+--------+--------+--------+--------+
|Date    |Customer  |StoreA  |StoreB  |StoreC  |StoreAct|StoreBct|StoreCct|
+--------+----------+--------+--------+--------+--------+--------+--------+
|01/12/15|Cust1     |3.80    |        |3.80    |1       |        |1       |
|01/12/15|Cust2     |2.40    |        |        |1       |        |1       |
|02/12/15|Cust2     |3.50    |        |1.50    |2       |        |        |

值StoreA是该日期所有交易的阳光,StoreAct是一天内该商店的交易数量。

经过一番搜索,我尝试了以下内容,但它没有产生预期的结果:

SELECT *
FROM (
    SELECT 
        Date, Customer, Value, Store, 1 as TransCount, Store+'ct' as storecount
    FROM SourceTable
) as s
PIVOT
(
    SUM(Value)
    FOR Customer IN (StoreA, StoreB, StoreC)
)AS pvt

PIVOT
(
 SUM(Transcount)
 FOR customer IN (StoreAct, StoreBct, StoreCct)
 )AS pvt

非常感谢所有和任何帮助,谢谢

1 个答案:

答案 0 :(得分:0)

您的数据透视表语句使用的是For Customer,而不是您尝试移动的实际列。

您还应使用Count() Over()窗口函数代替1 as TransCount来获取正确的计数。

这可以通过非常容易地替换select语句中的和和pivot语句中的列名来动态完成。

SELECT
    [Date],
    Customer,
    SUM(StoreA) StoreA,
    SUM(StoreB) StoreB,
    SUM(StoreC) StoreC,
    SUM(StoreAct) StoreAct,
    SUM(StoreBct) StoreBct,
    SUM(StoreCct) StoreCct
FROM
    (SELECT
        Date,
        Customer,
        Value,
        Store,
        COUNT(*) OVER (PARTITION BY date,customer,store) AS TransCount,
        Store + 'ct' AS storecount
     FROM
        SourceTable
    ) AS s 
PIVOT
( SUM(Value) FOR [Store] IN ([StoreA],[StoreB],[StoreC]) ) AS pvt 
PIVOT
( SUM(Transcount) FOR storecount IN ([StoreAct],[StoreBct],[StoreCct]) ) AS pvt
GROUP BY
    [Date],
    Customer
相关问题