我在SQL Server中有一个查询,该查询提供了如下所述的根据AGE和SEX进行策略计数。
SELECT
PLYMMRAGE as AGE,
MMRSEX as SEX,
COUNT(PLYNO) AS POLICYCOUNT
FROM
ADMGMPLYMSR
GROUP BY
PLYMMRAGE, MMRSEX
ORDER BY
MMRSEX DESC, PLYMMRAGE
此查询的输出是:
AGE SEX POLICYCOUNT
------------------------
2 M 10
4 M 9
5 M 6
8 M 0
1 F 4
2 F 6
4 F 0
但是我希望即使年龄不存在,该行也应该显示所有年龄段,政策计数为0到10岁。
AGE SEX POLICYCOUNT
-------------------------
1 M 0
2 M 10
3 M 0
4 M 9
5 M 6
6 M 0
7 M 0
8 M 0
9 M 0
10 M 0
1 F 4
2 F 6
4 F 0
以此类推。
如果该行的年龄不存在,如何插入计数为零的数据?即使使用程序也可以
答案 0 :(得分:2)
您可以同时使用LEFT JOIN
和coalesce
with ADMGMPLYMSR( PLYMMRAGE, MMRSEX, PLYNO ) as
(
select 2,'M',10 union all
select 4,'M', 9 union all
select 5,'M', 6 union all
select 8,'M', 0 union all
select 1,'M', 4 union all
select 2,'M', 6 union all
select 4,'M', 0
), t AS (
SELECT 1 AS n
UNION ALL
SELECT n+1 FROM t WHERE n+1<=10
)
SELECT COALESCE(PLYMMRAGE,n) as AGE, COALESCE(MMRSEX,'M') as SEX,
COUNT(PLYNO) AS POLICYCOUNT
FROM t
LEFT JOIN ADMGMPLYMSR ON PLYMMRAGE = n
GROUP BY coalesce(PLYMMRAGE,n), MMRSEX
ORDER BY coalesce(MMRSEX,'M') DESC, coalesce(PLYMMRAGE,n);