我有一個表t1並且有一列名爲days,所以我想將這些天分組1天到5天,6-15天和超過15天,然後計算每個組的計數,但是我不知道如何編寫sql,誰能告訴我?結果應該看起來像下面:想要一個SQL按值的範圍在oracle中分組值
Number Scope(days)
5 1-5
7 6-15
10 15+
我有一個表t1並且有一列名爲days,所以我想將這些天分組1天到5天,6-15天和超過15天,然後計算每個組的計數,但是我不知道如何編寫sql,誰能告訴我?結果應該看起來像下面:想要一個SQL按值的範圍在oracle中分組值
Number Scope(days)
5 1-5
7 6-15
10 15+
如果我沒有理解好,這可能是一個辦法:
with t1(days) as (
select 1 from dual union all
select 2 from dual union all
select 5 from dual union all
select 6 from dual union all
select 7 from dual union all
select 8 from dual union all
select 10 from dual union all
select 11 from dual union all
select 16 from dual union all
select 17 from dual union all
select 19 from dual union all
select 19 from dual
)
/* the query */
select count(*),
case
when days between 1 and 5 then '1-5'
when days between 6 and 15 then '6-15'
else '+15'
end
from t1
group by case
when days between 1 and 5 then '1-5'
when days between 6 and 15 then '6-15'
else '+15'
end
給出:
COUNT(*) CASE
---------- ----
3 1-5
4 +15
5 6-15
的想法是被什麼東西聚集那就是說每個數字所在的「組」,並且您可以使用CASE
輕鬆構建這樣的信息。
Accordin到Jarlh的建議,這可以被改寫爲
select count(*), the_group
from (
select case
when days between 1 and 5 then '1-5'
when days between 6 and 15 then '6-15'
else '+15'
end the_group
from t1
)
group by the_group
顯然,這假設你只有正數。
你有試過什麼嗎? – Aleksej
我完全不知道 – user2575502