假设我有以下(2)表:
[人员表]
ID 名称
约翰一
2 Suzy
3戴夫
[请求表]
ID 1stChoicePersonRequested 2ndChoicePersonRequested 3rdChoicePersonRequested
1 1 2 3
2 2 NULL NULL
3 1 2 NULL
4 3 1 1
我在查询中寻找的结果如下:
NameID 名称 NumTimeRequested
约翰一书4
2 Suzy 3
3戴夫2
我需要结果来计算每个人被请求的总次数,而不管它们包含哪些(3)列。在SQL 2008中执行此操作的最佳方法是什么?谢谢!
答案 0 :(得分:2)
SELECT P.ID NameID, Name, C NumTimeRequested
FROM
(
SELECT ID, COUNT(*) C
FROM (
SELECT [1stChoicePersonRequested] ID FROM [Request Table]
UNION ALL
SELECT [2ndChoicePersonRequested] ID FROM [Request Table]
UNION ALL
SELECT [3rdChoicePersonRequested] ID FROM [Request Table]
) R1
GROUP BY ID
) R2
JOIN [People Table] P ON R2.ID = P.ID
或者,你可以这样做:
SELECT
ID NameID,
Name,
(SELECT COUNT(*) FROM [Request Table] WHERE [1stChoicePersonRequested] = P.ID)
+ (SELECT COUNT(*) FROM [Request Table] WHERE [2ndChoicePersonRequested] = P.ID)
+ (SELECT COUNT(*) FROM [Request Table] WHERE [3rdChoicePersonRequested] = P.ID)
NumTimeRequested
FROM
[People Table] P
答案 1 :(得分:1)
;with R as
(
select PersonID
from [Request Table]
cross apply (values ([1stChoicePersonRequested]),
([2ndChoicePersonRequested]),
([3rdChoicePersonRequested])) as T(PersonID)
)
select R.PersonID as NameID,
P.Name,
count(*) as NumTimeRequested
from R
inner join [People Table] as P
on R.PersonID = P.ID
group by R.PersonID, P.Name
order by R.PersonID