基于收据类型的收据的SQL pivot datewise金额

时间:2015-05-13 05:49:32

标签: sql-server sql-server-2008 pivot

我正在寻找创建枢轴的帮助,它将根据收据类型显示收据的日期金额。

示例数据:

receipt_no  Receipt receipt_date    receipt_amount
0115D171073-CA  Cash Receipt    04/01/2015  338.00
0115D171074-CC  CreditCard Receipt  04/01/2015  185.00
0115D171075-CC  CreditCard Receipt  04/01/2015  187.00
0115D171076-CA  Cash Receipt    04/01/2015  250.00
0115D171077-CA  Cash Receipt    04/01/2015  25.00
0115D171078-CA  Cash Receipt    04/01/2015  6.50
0115D171079-CA  Cash Receipt    04/01/2015  35.00
0115D171080-CA  Cash Receipt    04/01/2015  210.00
0115D171081-CA  Cash Receipt    04/01/2015  25.00
0115D171082-CC  CreditCard Receipt  04/01/2015  209.00
0115D171083-CC  CreditCard Receipt  04/01/2015  280.00
0115D171084-CC  CreditCard Receipt  04/01/2015  25.00
0115D171085-CH  Cheque Receipt  27/12/2014  365.60
0115D171086-CH  Cheque Receipt  27/12/2014  365.60
0115D171087-CC  CreditCard Receipt  04/01/2015  372.50

预期结果为

Date      cash receipt       creditcard receipt      cheque receipt
27/12/2015     xxxxx.xx       xxxxx.xx               xxxx.xx
04/01/2015     xxxxx.xx       xxxxx.xx               xxxx.xx

SQL查询

SELECT * FROM(
SELECT 
CASE
WHEN receipt_no like '%CA%' THEN 'Cash Receipt'
WHEN receipt_no like '%CC%' THEN 'CreditCard Receipt'
WHEN receipt_no like '%CH%' THEN 'Cheque Receipt'
END AS Receipt, receipt_date, receipt_amount
FROM rpt_receipt_hdr
) Receipt
PIVOT
(
    SUM(receipt_amount)
    FOR receipt_date in (receipt_date)
)PIV

请帮我创建日期明智的支点

2 个答案:

答案 0 :(得分:2)

您不需要PIVOT,只有GROUP BY的{​​{1}}也可以。这样的事情。

CASE

答案 1 :(得分:0)

我已经想通了..

SELECT * FROM(
SELECT 
CASE
WHEN receipt_no like '%CA%' THEN 'Cash Receipt'
WHEN receipt_no like '%CC%' THEN 'CreditCard Receipt'
WHEN receipt_no like '%CH%' THEN 'Cheque Receipt'
END AS [Receipt], receipt_date, receipt_amount
FROM rpt_receipt_hdr
) Receipt
PIVOT
(
    SUM(receipt_amount)
    FOR [Receipt] in ([Cash Receipt],[CreditCard Receipt],[Cheque Receipt])
)PIV

这很好......