我有以下查询:
SELECT t.range,
Count(*)
FROM (
SELECT CASE
WHEN creditscore BETWEEN 300
AND 499
THEN '[300, 499]'
WHEN creditscore BETWEEN 500
AND 699
THEN '[500, 699]'
WHEN creditscore BETWEEN 700
AND 850
THEN '[700, 850]'
END AS range
FROM customer
) T
GROUP BY t.range;
这给了我以下内容:
CS range COUNT(*)
---------- ----------
[700, 850] 7
[500, 699] 13
我想要以下输出:
CS range COUNT(*)
---------- ----------
[300, 499] 0
[500, 699] 13
[700, 850] 7
任何人都可以帮助我吗?
更新
我执行了Justin提供的代码。它给了我以下内容:
DESCRIPTIO COUNT(*)
---------- ----------
[300, 499] 1
[700, 850] 7
[500, 699] 13
SQL> SELECT COUNT(*) FROM customer where creditscore BETWEEN 300 AND 499;
COUNT(*)
----------
0
答案 0 :(得分:1)
一种选择是做类似
的事情WITH ranges AS (
SELECT '[300, 499]' description, 300 min_val, 499 max_val FROM dual
UNION ALL
SELECT '[500, 699]' description, 500 min_val, 699 max_val FROM dual
UNION ALL
SELECT '[700, 850]' description, 700 min_val, 850 max_val FROM dual
)
SELECT r.description, count(creditscore)
FROM ranges r
LEFT OUTER JOIN customer c
ON (c.creditscore BETWEEN r.min_val AND r.max_val)
GROUP BY r.description
通常情况下,您希望设置一个包含范围的永久表,以防将来有人想要添加或修改它们。但是你可以像我在这里一样对查询中的范围进行硬编码。
答案 1 :(得分:0)
在这种情况下,您可以使用unpivot
。
你的回答 -
Select * From
(
Select Sum(Col1) "[300, 499]", Sum(Col2) "[500, 699]", Sum(Col3) "[700, 850]"
From (
Select Case
When Creditscore Between 300
And 499
Then 1 Else 0 End As Col1,
Case When Creditscore Between 500
And 699
Then 1 Else 0 End Col2,
Case When Creditscore Between 700
And 850
Then 1 Else 0 End Col3
From Customer
)
)
Unpivot
(
"Count"
For
"Description" In ("[300, 499]", "[500, 699]", "[700, 850]")
);
结果 -
Description Count
[300, 499] 0
[500, 699] 4
[700, 850] 3