我加入了6张桌子来收集我需要的所有信息。 我想要所有的Id,姓名,生日和种族。 有些Ids有2个或更多种族,这将导致id重复。 我正在考虑编写一个子查询,或者我可以只使用一个case语句,因为我之前已经尝试过case语句并且适用于另一个案例但我不能在这种情况下应用它。
我所拥有的是:
ID NAME Birthdays Ethnicity
4000 Pedram 11/11/1999 Middle East
4001 Carlos 11/11/1920 Spanish
4001 Carlos 11/11/1920 Native American
4002 Asia 11/22/1986 Polish
4002 Asia 11/22/1986 Native American
4002 Asia 11/22/1986 White/caucassian
我想说,如果任何Id重复和种族不同<>请给我这个:
ID NAME Birthdays Ethnicity
4000 Pedram 11/11/1999 Middle East
4001 Carlos 11/11/1920 Multiracial
4002 Asia 11/22/1986 multiracial
PS:种族在不同的表中,我加入了Person_table PS:为了能够将种族表连接到Person_table,我需要加入另外3个具有可以相互关联的pr键的表。 PS:我试过CASE WHEN Count(Id)> 1那么“多种族”的ELSE种族就像种族一样 并将所有种族都视为多种族。
任何帮助或想到的将是欣赏。
答案 0 :(得分:2)
您可以使用:
WITH CTE AS
(
SELECT *,
N = COUNT(*) OVER(PARTITION BY ID),
RN = ROW_NUMBER() OVER(PARTITION BY ID ORDER BY Ethnicity)
FROM dbo.YourTable
)
SELECT ID,
NAME,
Birthdays,
CASE WHEN N > 1 THEN 'Multiracial' ELSE Ethnicity END Ethnicity
FROM CTE
WHERE RN = 1;
答案 1 :(得分:1)
SELECT
id, name, Birthdays,
IIF(COUNT(DISTINCT Ethnicity) > 1, 'Multiracial', MIN(Ethnicity)) as Ethnicity
FROM
Table
GROUP BY
id, name, Birthdays
SELECT
id, name, Birthdays,
CASE WHEN COUNT(DISTINCT Ethnicity) > 1 THEN 'Multiracial' ELSE MIN(Ethnicity) END as Ethnicity
FROM
Table
GROUP BY
id, name, Birthdays
答案 2 :(得分:1)
这个可能不是最有效但它有效。只需将您的派生表替换为下面的t:
SELECT DISTINCT t.id, t.name,
CASE WHEN cnt = 1 THEN ethnicity
ELSE 'Multiracial' END AS ethnicity
FROM t
INNER JOIN
(SELECT id, COUNT(DISTINCT ethnicity) AS cnt
FROM t
GROUP BY id) sub
ON t.id = sub.id