我有3张桌子互相联系,以获取我的客户的信息。我的一些客户是多种族的,这使得表有重复的行。
我想知道我是否可以识别一个新值,并说一个ID是否重复,在比赛中给了我Multiracial作为值?
我有这个:
ID Name Age Race
4000 Duc 25 Philipino
4000 Duc 25 Chinese
4001 Daniel 36 African American
4002 Nicole 20 White
4002 Nicole 20 Middle East
我想要这个
ID Name Age Race
4000 Duc 25 Multiracial
4001 Daniel 36 African American
4002 Nicole 20 Multiracial
我非常感谢任何帮助
答案 0 :(得分:1)
你可以这样做(应该适用于MS SQL和MySQL):
SELECT ID,Name,Age, CASE WHEN COUNT(Race)>1 THEN 'Mulitiracial' ELSE MAX(Race) END Race
FROM Src
GROUP BY ID,Name,Age
要测试您的数据(仅在MS SQL中使用CTE),我使用了以下内容:
WITH Src AS
(
SELECT * FROM (VALUES
(4000, 'Duc ', 25, 'Philipino' ),
(4000, 'Duc ', 25, 'Chinese' ),
(4001, 'Daniel', 36, 'African American' ),
(4002, 'Nicole', 20, 'White ' ),
(4002, 'Nicole', 20, 'Middle East ' )
)T (ID,Name,Age,Race)
)
SELECT ID,Name,Age, CASE WHEN COUNT(Race)>1 THEN 'Mulitiracial' ELSE MAX(Race) END Race
FROM Src
GROUP BY ID,Name,Age
答案 1 :(得分:0)
;WITH CTE
AS
(SELECT ID,NAME,AGE,RACE,COUNT(*) OVER (PARTITION BY ID,NAME,AGE ORDER BY (SELECT NULL)) AS CNT
FROM
#TEMP
)
SELECT ID,NAME,AGE,CASE WHEN CNT>1 THEN 'MULTIRACILA' ELSE RACE END
FROM CTE
GROUP BY
ID,NAME,AGE,CASE WHEN CNT>1 THEN 'MULTIRACILA' ELSE RACE END