如何在连接两个或三个表时避免重复值?

时间:2016-05-13 07:24:56

标签: sql-server

我有两张桌子,我想加入他们的两张ID。

Household Info                             
1
2
3

Household Members
1
1
1
2
3
3
3
3
3

正如您在我的屏幕截图中注意到的那样,值一遍又一遍地重复着。我想要的输出是,我想要查询:

Household Info.HID                Household Members.HID
1                                 1
                                  1
                                  1
2                                 2
3                                 3
                                  3
                                  3
                                  3
                                  3

enter image description here

由于表家庭信息中只有3个HID,而家庭成员表中有三个:1,1:2和5:3

希望你能帮我解决这个问题:3 编辑:我使用 Microsoft Access 作为RDBMS

2 个答案:

答案 0 :(得分:0)

对于支持CTE的RDBMS ......

DECLARE @Household  TABLE 
    ( Household  VARCHAR(10))
;

INSERT INTO @Household
    ( Household )
VALUES
    (1),
    (2),
    (3)
;


declare @HouseholdMembers TABLE 
    ( HouseholdMembers  VARCHAR(10))
;

INSERT INTO @HouseholdMembers
    ( HouseholdMembers )
VALUES
    (1),
    (1),
    (1),
    (2),
    (3),
    (3),
    (3),
    (3),
    (3)
;

Select 
CASE WHEN RN = 1 THEN Household ELSE '' END Household,
HouseholdMembers 
from (
select h.Household,
hm.HouseholdMembers,
ROW_NUMBER()OVER(PARTITION BY hm.HouseholdMembers ORDER BY h.Household)RN from @Household h
LEFT JOIN @HouseholdMembers hm
ON hm.HouseholdMembers = h.Household)T

答案 1 :(得分:0)

您没有提到您使用的是RDBMS。

我认为您可以根据自己的情况使用数据透视表:

http://www.codeproject.com/Tips/500811/Simple-Way-To-Use-Pivot-In-SQL-Query

或使用分组:

select c2, c3
  , sum( case when no_of_days <= 7 then 1 else 0 end) as dlt8
  , sum( case when no_of_days between 8 and 14 then 1 else 0 end) as d8to14
  , sum( case when no_of_days between 15 and 21 then 1 else 0 end) as d15to21
  , sum( case when no_of_days between 22 and 27 then 1 else 0 end) as d22to27
from mytable
group by c2, c3
order by c2, c3;

在这里,您可以找到与您的问题相似的答案:

Dynamic alternative to pivot with CASE and GROUP BY

修改1

如果你需要这样的东西:

SubjectID       StudentName
----------      -------------
1               Mary
1               John
1               Sam
2               Alaina
2               Edward

我预期的结果是:

SubjectID       StudentName
----------      -------------
1               Mary, John, Sam
2               Alaina, Edward

您可以查看此示例:

Concatenate many rows into a single text string?

修改2

我记得的最后一个选项就是这个。它适用于MySQL,但您可以重用逻辑:

MySQL JOIN - Return NULL for duplicate results in left table