添加总计数的总行数

时间:2016-10-04 14:02:27

标签: oracle

我正在使用此查询:

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 个答案:

答案 0 :(得分: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);