我有一张患者表,如下所示:
患者
Name Gender DOB
Student A M 03-mar-2001
Student B F 08-dec-1985
Student C F 12-sep-1990
Student D M 20-may-1981
我想有一个SQL语句来显示结果如下:
Gender 0-19 20-29 30-39
M 1 0 1
F 0 2 0
答案 0 :(得分:0)
请查看以下查询
CREATE TABLE #t1 (NAME VARCHAR(100),Gender VARCHAR(10),DOB DATE)
INSERT INTO #t1(NAME,Gender,DOB) VALUES('Student A','M','03-mar-2001')
INSERT INTO #t1(NAME,Gender,DOB) VALUES('Student B','F','08-dec-1985')
INSERT INTO #t1(NAME,Gender,DOB) VALUES('Student C','F','12-sep-1990')
INSERT INTO #t1(NAME,Gender,DOB) VALUES('Student D','M','20-may-1981')
SELECT Gender , SUM(CASE WHEN DATEDIFF(yy,DOB,GETDATE()) BETWEEN 0 AND
20 THEN 1 ELSE 0 END) [0-19],
SUM(CASE WHEN DATEDIFF(yy,DOB,GETDATE()) BETWEEN 21 AND 30
THEN 1 ELSE 0 END) [20-29],
SUM(CASE WHEN DATEDIFF(yy,DOB,GETDATE()) BETWEEN 31 AND 40
THEN 1 ELSE 0 END) [30-39]
FROM #t1
GROUP BY Gender