使用PHP Mysql CASE的每日销售报告

时间:2016-06-14 09:25:06

标签: php mysql

我需要根据以下查询获取每日销售报告..

这是我的表结构

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';

所以请任何人帮助我。

提前致谢

1 个答案:

答案 0 :(得分: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';
相关问题