amount_usd paytype SendItemDateTime1
5.00 google 2015-04-01
2.00 google 2015-04-01
5.00 transfer 2015-04-01
15.00 google 2015-04-01
5.00 google 2015-04-01
2.00 google 2015-04-02
60.00 google 2015-04-02
60.00 google 2015-04-02
5.00 google 2015-04-03
上面是我的演示数据库,其中有amount_usd,paytype和SendItemDateTime1列。当我在下面的查询中使用数据透视时,它在下面显示结果,而不是SendItemDateTime1分组...是什么问题?
select amount_usd, paytype, SendItemDateTime1 from tblMobile_RequestOrderLog
where status = 1 and sendstatus = 1 and enable = 1
and SendItemDateTime1 between '4/1/2015' and '4/30/2015'
order by SendItemDateTime1
以下是上面查询的结果。
SenditemDateTime1 google mol molpay molstore paypal transfer
2015-04-01 15.00 NULL NULL NULL NULL NULL
2015-04-01 5.00 NULL NULL NULL NULL NULL
2015-04-01 15.00 NULL NULL NULL NULL NULL
2015-04-01 5.00 NULL NULL NULL NULL NULL
2015-04-01 60.00 NULL NULL NULL NULL NULL
2015-04-01 10.00 NULL NULL NULL NULL NULL
以下是我想要的...
SendItemDate google mol molpay molstore paypal transfer
2015-04-01 32 0 0 0 0 5
2015-04-02 122 0 0 0 0 0
2015-04-03 5 0 0 0 0 0
抱歉,第一次在这里发问...
编辑
这对我有用“在哪里”子句:
SELECT SendItemDateTime1, COALESCE([google], 0), COALESCE([transfer], 0),
COALESCE([paypal], 0),COALESCE([molpay], 0)
FROM (Select SendItemDateTime1, paytype, amount_usd
from tblMobile_RequestOrderLog
where gameidn = 248 and status = 1 and sendstatus = 1 and enable = 1
and SendItemDateTime1 between '4/1/2015 12:00:00 AM'
and '4/30/2015 11:59:59'
) X
PIVOT
(
SUM(amount_usd)
for [paytype] IN ([google],[transfer],[paypal],[molpay])
) piv;
最佳答案
您可以使用以下查询在第一个表格中旋转数据-您只需要明确列出所有付款类型列即可。我假设SUM()
作为要应用的聚合:
SELECT SendItemDateTime1, [google],[transfer],[paypal],[molpay]
FROM MyTable
PIVOT
(
SUM(amount_usd)
for [paytype] IN ([google],[transfer],[paypal],[molpay])
) piv;
SqlFiddle here
编辑,关于我在哪里过滤
如果可以将筛选谓词应用于最后一列,则可以在PIVOT之后应用
WHERE
。否则,如果需要在非透视列中进行过滤,则可以使用CTE或派生表。这是CTE中的预过滤器和WHERE后过滤器的示例:-- Prefilter of non-pivot columns done in CTE or Derived table
WITH cte AS
(
SELECT [amount_usd], [paytype], [SendItemDateTime1]
FROM MyTable
WHERE [amount_usd] > 2
)
SELECT SendItemDateTime1, COALESCE([google], 0), COALESCE([transfer], 0),
COALESCE([paypal], 0),COALESCE([molpay], 0)
FROM cte
PIVOT
(
SUM(amount_usd)
for [paytype] IN ([google],[transfer],[paypal],[molpay])
) piv
-- Post filter of pivot columns done on the final projection
WHERE SendItemDateTime1 > '2015-01-01';
Updated Fiddle
关于c# - 我在哪里将WHERE子句放在具有日期交易的PIVOT中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30183225/