鉴于下表:
PERSON IS_EMPLOYED IS_MARRIED IS_STUDENT
John Y N Y
Tom N Y N
Rob N N N
Ron Y Y Y
如何计算每个人的总Y和N,以便得到以下结果?
PERSON TOTAL_Y TOTAL_N
John 2 1
Tom 1 2
Rob 0 3
Ron 3 0
我正在使用Access,我可以使用VBA来做,但我想知道是否有一个可以使用SQL实现的更快的解决方案。
答案 0 :(得分:1)
您可以尝试以下查询
SELECT
Person,
IFF(IS_EMPLOYED = 'Y', 1,0) + IFF(IS_MARRIED = 'Y', 1,0)+ IFF(IS_STUDENT = 'Y', 1,0) AS TOTAL_Y,
IFF(IS_EMPLOYED = 'N', 1,0) + IFF(IS_MARRIED = 'N', 1,0)+ IFF(IS_STUDENT = 'N', 1,0) AS TOTAL_N
FROM Persons;
答案 1 :(得分:1)
有几种方法可以做到这一点。联合查询是一个不错的选择,因为它很容易扩展,或者在将来添加更多计算:
SELECT
person,
sum(iif(yesno='Y', 1, 0)) as Total_Y,
sum(iif(yesno='N', 1, 0)) as Total_N
FROM
(
SELECT person, is_employed as yesno FROM table
UNION ALL
SELECT person, is_married FROM table
UNION ALL
SELECT person, is_student FROM table
) AS yesnoquery
GROUP BY person