我需要计算一列中的不同值。它是Char数据类型。我在oracle中编写了我的代码,但是我无法更改SQL Server中的语法;
这有效:
Select l.name, l.address,
SUM(DECODE(L.SEX, 'M', 1, 0)) MALE_TOTAL,
SUM(DECODE(L.SEX, 'F', 1, 0)) FEMALE_TOTAL,
SUM(DECODE(L.SEX, 'U', 1, 0)) UNKNOWN_TOTAL
From personnel
非常感谢
答案 0 :(得分:1)
您想要的SQL标准方法是:
Select l.name, l.address,
SUM(CASE WHEN L.SEX = 'M' THEN 1 ELSE 0 END) MALE_TOTAL,
SUM(CASE WHEN L.SEX = 'F' THEN 1 ELSE 0 END) FEMALE_TOTAL,
SUM(CASE WHEN L.SEX = 'U' THEN 1 ELSE 0 END) UNKNOWN_TOTAL
From personnel
group by l.name, l.address;
请注意GROUP BY
。如果你想要每个名称/地址一行,那么你需要这个。否则,请从SELECT
:
Select SUM(CASE WHEN L.SEX = 'M' THEN 1 ELSE 0 END) MALE_TOTAL,
SUM(CASE WHEN L.SEX = 'F' THEN 1 ELSE 0 END) FEMALE_TOTAL,
SUM(CASE WHEN L.SEX = 'U' THEN 1 ELSE 0 END) UNKNOWN_TOTAL
From personnel;
答案 1 :(得分:0)
您可以使用IIF 2012 +
https://docs.microsoft.com/en-us/sql/t-sql/functions/logical-functions-iif-transact-sql
SELECT
SUM(IIF(L.SEX = 'M', 1, 0)) MALE_TOTAL,
SUM(IIF(L.SEX = 'F', 1, 0)) FEMALE_TOTAL,
SUM(IIF(L.SEX = 'U', 1, 0)) UNKNOWN_TOTAL
FROM personnel
OR CASE
SELECT
SUM(case when L.SEX = 'M' then 1 else 0 end)) MALE_TOTAL,
SUM(case when L.SEX = 'F' then 1 else 0 end) FEMALE_TOTAL,
SUM(case when L.SEX = 'U' then 1 else 0 end) UNKNOWN_TOTAL
FROM personnel