ご覧のとおり、これには時間がかかります。代替案はありますか?group by 句で列エイリアスを使用しようとしましたが、役に立ちませんでした。
select count(callid) ,
case
when callDuration > 0 and callDuration < 30 then 1
when callDuration >= 30 and callDuration < 60 then 2
when callDuration >= 60 and callDuration < 120 then 3
when callDuration >= 120 and callDuration < 180 then 4
when callDuration >= 180 and callDuration < 240 then 5
when callDuration >= 240 and callDuration < 300 then 6
when callDuration >= 300 and callDuration < 360 then 7
when callDuration >= 360 and callDuration < 420 then 8
when callDuration >= 420 and callDuration < 480 then 9
when callDuration >= 480 and callDuration < 540 then 10
when callDuration >= 540 and callDuration < 600 then 11
when callDuration >= 600 then 12
end as duration
from callmetatbl
where programid = 1001 and callDuration > 0
group by case
when callDuration > 0 and callDuration < 30 then 1
when callDuration >= 30 and callDuration < 60 then 2
when callDuration >= 60 and callDuration < 120 then 3
when callDuration >= 120 and callDuration < 180 then 4
when callDuration >= 180 and callDuration < 240 then 5
when callDuration >= 240 and callDuration < 300 then 6
when callDuration >= 300 and callDuration < 360 then 7
when callDuration >= 360 and callDuration < 420 then 8
when callDuration >= 420 and callDuration < 480 then 9
when callDuration >= 480 and callDuration < 540 then 10
when callDuration >= 540 and callDuration < 600 then 11
when callDuration >= 600 then 12
end
編集:私は本当に単一のケースソースを持つ方法を尋ねるつもりでしたが、とにかくケースの変更は大歓迎です(ただし、間隔はおそらく変更され、自動的に生成される可能性があるためあまり役に立ちません)。
一部の人々が考えているように、 callDuration は実際にはフロートであるため、リストされているソリューションの一部は、間隔から値を除外することにより、私のユース ケースには有効ではありません。
教訓:
ケース式のパターンを探して、可能で価値がある場合はそれを減らします
case when callDuration > 0 AND callDuration < 30 then 1 when callDuration > 600 then 12 else floor(callDuration/60) + 2 end end as duration
インライン ビューを使用してケースのソースを 1 つにする
select count(d.callid), d.duration from ( select callid , case when callDuration > 0 AND callDuration < 30 then 1 when callDuration > 600 then 12 else floor(callDuration/60) + 2 end end as duration from callmetatbl where programid = 1001 and callDuration > 0 ) d group by d.duration
または、一般的なテーブル式を使用します
with duration_case as ( select callid , case when callDuration > 0 AND callDuration < 30 then 1 when callDuration > 600 then 12 else floor(callDuration/60) + 2 end end as duration from callmetatbl where programid = 1001 and callDuration > 0 ) select count(callid), duration from duration_case group by duration
または、ユーザー定義関数を使用します(これまでの例はありません:-))
または、ルックアップ テーブルと結合を使用します。
DECLARE @t TABLE(durationFrom float, durationTo float, result INT) --populate table with values so the query works select count(callid) , COALESCE(t.result, 12) from callmetatbl JOIN @t AS t ON callDuration >= t.durationFrom AND callDuration < t.durationTo where programid = 1001 and callDuration > 0
多くの人が質問のさまざまな部分をカバーしているため、受け入れられた回答を選択するのに非常に苦労しています(そして、私はそれが単純な回答の単純な質問だと思っていました:-)、混乱して申し訳ありません)。