2016-10-04 120 views
1

我與此查詢工作:加入總一行總和計數

SELECT PAS.NAME, 
(
    SELECT COUNT(*) FROM CUSOMERS WHERE C_ID = 90 
    AND CONTRACT_TYPE = 80 
    AND CONTRACT_DATE >= TO_DATE('20160101', 'YYYYMMDD') 
    AND CONTRACT_DATE <= TO_DATE('20161231', 'YYYYMMDD') 
    AND ORDER_ID = ORDERS.ID 
    AND STATUS = 1 
) AS ORDER_SHIPPED_COUNT FROM ORDERS INNER JOIN PAS ON ORDERS.ID = PAS.ID 
WHERE ORDERS.COUNTRY = 123 
AND ORDERS.PAYMENT = 30 
AND ORDERS.CONTRACT_TYPE = 80 
AND PAS.NAME LIKE 'HAS SHIPPED - %'; 

結果我得到的是以下幾點:

NAME       ORDER_SHIPPER_COUNT 
HAS SHIPPED ON TIME   654 
HAS SHIPPED LATE    23 
HAS SHIPPED AND LOST   2 

而且我想結果是這樣

NAME       ORDER_SHIPPER_COUNT 
HAS SHIPPED ON TIME   654 
HAS SHIPPED LATE    23 
HAS SHIPPED AND LOST   2 
TOTAL      679 

感謝所有

回答

1
with t as (
SELECT PAS.NAME, 
(
    SELECT COUNT(*) FROM CUSOMERS WHERE C_ID = 90 
    AND CONTRACT_TYPE = 80 
    AND CONTRACT_DATE >= TO_DATE('20160101', 'YYYYMMDD') 
    AND CONTRACT_DATE <= TO_DATE('20161231', 'YYYYMMDD') 
    AND ORDER_ID = ORDERS.ID 
    AND STATUS = 1 
) AS ORDER_SHIPPED_COUNT FROM ORDERS INNER JOIN PAS ON ORDERS.ID = PAS.ID 
WHERE ORDERS.COUNTRY = 123 
AND ORDERS.PAYMENT = 30 
AND ORDERS.CONTRACT_TYPE = 80 
AND PAS.NAME LIKE 'HAS SHIPPED - %') 
select * 
from t 
union all 
select 'TOTAL',sum(ORDER_SHIPPER_COUNT) from t; 

如果你通過查詢獲取唯一的記錄,那麼你也可以使用下面的查詢,而無需使用UNION ALL:

with t as (
SELECT PAS.NAME, 
(
    SELECT COUNT(*) FROM CUSOMERS WHERE C_ID = 90 
    AND CONTRACT_TYPE = 80 
    AND CONTRACT_DATE >= TO_DATE('20160101', 'YYYYMMDD') 
    AND CONTRACT_DATE <= TO_DATE('20161231', 'YYYYMMDD') 
    AND ORDER_ID = ORDERS.ID 
    AND STATUS = 1 
) AS ORDER_SHIPPED_COUNT FROM ORDERS INNER JOIN PAS ON ORDERS.ID = PAS.ID 
WHERE ORDERS.COUNTRY = 123 
AND ORDERS.PAYMENT = 30 
AND ORDERS.CONTRACT_TYPE = 80 
AND PAS.NAME LIKE 'HAS SHIPPED - %') 
select nvl(name,'TOTAL') name, 
     sum(ORDER_SHIPPER_COUNT) ORDER_SHIPPER_COUNT 
from t 
group by rollup(name); 
+0

謝謝!!它的工作 – Chrix1387

+0

你可以檢查第二個查詢,如果它也適用於你。 – hemalp108