我有以下查询,并且对于我的生活已经忘记了如何将两列合并以创建“总计”列
SELECT username as 'username',
count (case when casestype <> 'car'
OR casestype <> 'van'
OR casestype <> 'bike'
OR casestype <> 'NONE'
THEN 1 ELSE NULL END) as 'non-auto',
count (case when casestype = 'car'
OR casestype= 'van'
OR casestype = 'bike'
THEN 1 ELSE NULL END) as 'auto'
FROM Case WITH (NOLOCK)
WHERE CaseDate BETWEEN '01 may 2016' AND '31 may 2016')
GROUP BY username
我想要一个非自动+自动
的总列答案 0 :(得分:4)
SELECT username,
sum(case when casestype not in ('car', 'van', 'bike', 'NONE')
then 1 else 0
end) as non_auto,
sum(case when casestype in ('car', 'ban', 'bike') then 1 else 0
end) as auto,
sum(case when casestype <> 'NONE' then 1 else 0 end) as total
FROM [Case]
WHERE CaseDate BETWEEN '2016-05-01' and '2016-05-31'
GROUP BY username;
其他建议:
in
和not in
比一系列or
语句更具可读性。total
需要单独计算。如果要使用列别名,则需要子查询或CTE。