我有一张死亡表,其中每个personID显示死亡。还有一栏有关死亡的原因以及他/她去世的日期。
我需要计算因疾病,意外,自杀等而死亡的所有人。
我希望我的输出是这样的:
| Illness | Accident | Suicide |
| 32 | 55 | 3 |
我可以轻松创建这样的视图:
CREATE VIEW viewDeaths AS
SELECT COUNT(personID) AS Illness
WHERE Reason = 'Illness';
它会显示正确,但我如何在多个条件下进行?
主要目的是在C#应用程序的图表上显示每个原因的不同值
答案 0 :(得分:2)
只需使用多个子查询:
CREATE VIEW viewDeaths AS
SELECT Illness = (SELECT COUNT(*) FROM dbo.Deaths d
WHERE d.Reason = 'Illness'),
Accident = (SELECT COUNT(*) FROM dbo.Deaths d
WHERE d.Reason = 'Accident'),
Suicide = (SELECT COUNT(*) FROM dbo.Deaths d
WHERE d.Reason = 'Suicide')
答案 1 :(得分:0)
这样:
CREATE VIEW viewDeaths AS
SELECT Reason, COUNT(personID) AS Illness
-- WHERE Reason IN (.....)
GROUP BY Reason
答案 2 :(得分:0)
由于它是一个视图,因此您无法使用动态SQL,因此静态PIVOT
或CASE
表达式将是最佳方式:
CREATE VIEW viewDeaths
AS
SELECT SUM(CASE WHEN Reason = 'Illness' THEN 1 ELSE 0 END) Illness,
SUM(CASE WHEN Reason = 'Accident' THEN 1 ELSE 0 END) Accident,
SUM(CASE WHEN Reason = 'Suicide' THEN 1 ELSE 0 END) Suicide
FROM dbo.Deaths;