[英]Oracle SQL query to get output in specific format
我有以下數據的Oracle數據庫表“ mytable”
Sr_NO Name Status Date
121 HP OK 12/06/2018
122 Dell OK 15/06/2018
123 MAC NOK 30/07/2018
124 Apple NOK 03/09/2018
125 MI NOK 04/09/2018
126 Oppo NOK 05/09/2018
127 Vivo OK 06/09/2018
我想以以下格式獲取輸出-
Category Count OK NOK
Till 30th Jul 3 2 1
After 30th Jul 4 1 3
Total 7 3 4
您可以使用條件聚合來獲取列和grouping sets
來獲取其他行:
select (case when date <= '2018-07-30' then 'Till 30th Jul'
else 'After 30th Jul'
end) as category,
count(*),
sum(case when status = 'OK' then 1 else 0 end) as OK,
sum(case when status = 'NOK' then 1 else 0 end) as NOK
from t
group by grouping sets ( ( (case when date <= '2018-07-30' then 'Till 30th Jul'
else 'After 30th Jul'
end)
),
()
);
您可以將total
添加為類別(在您的情況下),使用與NULL
的比較:
select (case when date is null then 'Total'
when date <= '2018-07-30' then 'Till 30th Jul'
else 'After 30th Jul'
end) as category,
您的數據中沒有NULL
日期,所以很好。 否則,您應該使用GROUPING()
。
請勿將DATE
和COUNT
類的Oracle關鍵字用作列名。 我將其更改為DT
和CT
。
對於GROUP BY ROLLUP
,這是一項簡單的工作,在您創建了附加列FLAG
以顯示每行所屬的組之后。 我在“ 2018年7月30日之前”將標志創建為'b'
”-否則標志為NULL。 (這允許我也使用ORDER BY
的標志,因為默認情況下, FLAG
排序為NULLS LAST
。)
請記住,在運行查詢之前,請完全刪除 WITH
子句,並使用實際的表名和列名。
alter session set nls_date_format = 'dd/mm/yyyy';
with
test_data (sr_no, name, status, dt) as (
select 121, 'HP' , 'OK' , to_date('12/06/2018') from dual union all
select 122, 'Dell' , 'OK' , to_date('15/06/2018') from dual union all
select 123, 'MAC' , 'NOK', to_date('30/07/2018') from dual union all
select 124, 'Apple', 'NOK', to_date('03/09/2018') from dual union all
select 125, 'MI' , 'NOK', to_date('04/09/2018') from dual union all
select 126, 'Oppo' , 'NOK', to_date('05/09/2018') from dual union all
select 127, 'Vivo' , 'OK' , to_date('06/09/2018') from dual
)
select case grouping_id(flag) when 0
then case flag when 'b' then 'Till 30th July'
else 'After 30th July'
end
else 'Total'
end as category
, count(status) as ct
, count(case status when 'OK' then 0 end) as ok
, count(case status when 'NOK' then 0 end) as nok
from ( select sr_no, name, status, dt,
case when dt <= date '2018-07-30' then 'b' end as flag
from test_data
)
group by rollup(flag)
order by grouping_id(flag), flag
;
CATEGORY CT OK NOK
--------------- ---------- ---------- ----------
Till 30th July 3 2 1
After 30th July 4 1 3
Total 7 3 4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.