我有以下查询,其中输出称呼为先生/女士
的成员的数量和百分比我想将结果重命名为'男'而不是'先生'和女性,而不是'女士'。
这可能是一个相当简单的案例,但无法让它发挥作用......
SELECT AspNetUsers.Salutation AS Sex, COUNT(AspNetUsers.Salutation) as Total,
CAST(ROUND((COUNT(AspNetUsers.Salutation)* 100.0 / (SELECT COUNT(*) FROM Member, AspNetUsers WHERE Member.AspNetUserId = AspNetUsers.Id)),1) AS NUMERIC(36,1)) AS Percentage
FROM Member, AspNetUsers
WHERE Member.AspNetUserId=AspNetUsers.Id
GROUP BY Salutation
答案 0 :(得分:2)
您绝对认为它是一个简单的案例表达式,但您还需要按相同的案例表达式进行分组。
SELECT
CASE
WHEN AspNetUsers.Salutation = 'Mr' THEN 'Male'
WHEN AspNetUsers.Salutation = 'Ms' THEN 'Female'
ELSE 'Other' -- this is of course optional
END AS Sex,
COUNT(AspNetUsers.Salutation) as Total,
CAST(ROUND((COUNT(AspNetUsers.Salutation)* 100.0 / (SELECT COUNT(*) FROM Member JOIN AspNetUsers ON Member.AspNetUserId = AspNetUsers.Id)),1) AS NUMERIC(36,1)) AS Percentage
FROM Member
JOIN AspNetUsers ON Member.AspNetUserId = AspNetUsers.Id
GROUP BY
CASE
WHEN AspNetUsers.Salutation = 'Mr' THEN 'Male'
WHEN AspNetUsers.Salutation = 'Ms' THEN 'Female'
ELSE 'Other' -- this is of course optional
END;
通过使用公用表表达式不必重复case表达式和窗口计数而不是子查询,可以改进查询,但我会留给你。