2016-06-14 118 views
1

我需要得到下面的查詢基礎上,每日銷售報告..每日銷售報告與PHP的MySQL CASE

這是我的表結構

orderid resid payment_type ordertotalprice orderdate 
1  10  cod    50    2016-06-14 
2  10  cod    10    2016-06-14 
3  10  creditcard  40    2016-06-14 
4  10  cod    30    2016-06-14 
5  10  creditcard  20    2016-06-14 
6  10  cod    10    2016-06-14 
7  10  creditcard  20    2016-06-14 
8  11  cod    10    2016-06-14 

我需要使用如下表上面的輸出結果。

resid total_orders_cnt total_sales total_orders_cash total_sales_cash total_orders_cc total_sales_cc 
10 7    180   4     100     3    80 
11 1    10   1     10      0    0 

我正在使用下面的查詢,但它沒有得到確切的結果我想要什麼。

SELECT COUNT(orderid) AS total_orders_cnt, SUM(ordertotalprice) AS total_sales, 
     SUM(CASE WHEN (payment_type= 'cod') THEN 1 ELSE 0 END) AS total_orders_cash, 
     CASE WHEN (payment_type= 'cod') THEN SUM(ordertotalprice) ELSE 0 END AS total_sales_cash, 
     SUM(CASE WHEN (payment_type = 'creditcard') THEN 1 ELSE 0 END) total_orders_cc, 
     CASE WHEN (payment_type = 'creditcard') THEN SUM(ordertotalprice) ELSE 0 END AS total_sales_cc 
FROM order WHERE resid='10' AND orderdate = '2016-06-14'; 

所以請任何人幫助我。

在此先感謝

+0

請註明每個問題一個答案,如果他們是問題的解決者和您批准。您可以使用[綠色複選標記](http://meta.stackexchange.com/q/5234),如下面的Giorgos'或任何其他人。沒有你的問題,推動20,已被接受。謝謝。 – Drew

回答

1

試試這個方法:

SELECT COUNT(orderid) AS total_orders_cnt, 
     SUM(ordertotalprice) AS total_sales, 
     SUM(CASE WHEN payment_type = 'cod' THEN 1 ELSE 0 END) AS total_orders_cash, 
     SUM(CASE WHEN payment_type = 'cod' THEN ordertotalprice END) AS total_sales_cash, 
     SUM(CASE WHEN payment_type = 'creditcard' THEN 1 ELSE 0 END) total_orders_cc, 
     SUM(CASE WHEN payment_type = 'creditcard' THEN ordertotalprice END) AS total_sales_cc 
FROM order 
WHERE resid = '10' AND orderdate = '2016-06-14'; 
+0

它的工作正常。謝謝 – mikejohnvino

+0

@mikejohnvino很高興我能夠幫助。如果它幫助你解決你的問題,請將它標記爲或接受任何其他答案。 –