使用一个SQL表的多个SELECT语句

时间:2019-01-11 03:36:21

标签: sql multiple-select

希望你一切都好。 实际上,我正在一个项目上,需要每天计算TOTAL_SALE,TOTAL_CASH和TOTAL_CREDIT...。 以下是我的查询,但是我的查询给出了TOTAL_CASH和TOTAL_CREDIT中的总付款总额,因为它必须是这样。.

+------------+------------+--------------+
| TOTAL_SALE | TOTAL_CASH | TOTAL_CREDIT |
+------------+------------+--------------+
|       1000 |        250 |          750 |
+------------+------------+--------------+ 

以下是我的SQL查询:-

SELECT

 sss.creation_date , SUM(sss.payment_due) as 'Total Sale', 
 (SELECT SUM(s.payment_due) FROM sale s WHERE s.payment_method LIKE '%Cash_%' AND s.shop='10' 
  AND s.DateNum >='20181201000000' AND s.DateNum <='20181231235959' GROUP BY s.creation_date)as 'Total Cash' , 

  (SELECT SUM(ss.payment_due) FROM sale ss WHERE ss.payment_method LIKE '%cCredit_%' AND ss.shop='10' 
  AND ss.DateNum >='20181201000000' AND ss.DateNum <='20181231235959' GROUP BY ss.creation_date)as 'Total Credit' , 

 SUM(discount) as 'Total Discount' , SUM(number_of_item_purchased) as 'Total Sold'

 FROM Sale sss

 WHERE sss.shop='10' AND sss.DateNum >='20181201000000' AND sss.DateNum <='20181231235959'

 GROUP BY sss.creation_date

1 个答案:

答案 0 :(得分:0)

您可以在下面尝试使用条件聚合

SELECT
 SUM(payment_due) as 'Total Sale', 
 SUM(case when payment_method LIKE '%Cash_%' then s.payment_due end) as 'Total Cash' , 
 SUM(case when payment_method LIKE '%cCredit_%' then payment_due end) as 'Total Credit', 
 SUM(discount) as 'Total Discount' , 
 SUM(number_of_item_purchased) as 'Total Sold'
 FROM Sale 
 WHERE shop='10' AND DateNum >='20181201000000' AND DateNum <='20181231235959'