Sql连接两个表

时间:2015-07-23 13:43:56

标签: sql sql-server sql-server-2008 sql-server-2008-r2

从sql检索一些数据时我遇到了一个问题。

我有两个表table1和table2。

Table1是我的主表。请参阅下表结构。enter image description here

表2结构

enter image description here

我需要输出像

这样的输出

enter image description here

请帮帮我

谢谢!

1 个答案:

答案 0 :(得分:2)

您的要求非常不明确,但根据您的评论,您使用Table1作为根据喜欢,评论和观看次数收到的徽章的查找表。

您可以为每个元素执行Cross Apply这些查找:

Select  UserId, Likes, Comments, Views, 
        LikeBadges.Count + CommentBadges.Count + ViewBadges.Count As NoOfBadges
From    Table2
Cross Apply
(
    Select  Count(*) as Count
    From    Table1
    Where   Table1.Action = 'Likes'
    And     Table2.Likes >= Table1.Count
) As LikeBadges
Cross Apply
(
    Select  Count(*) as Count
    From    Table1
    Where   Table1.Action = 'Comments'
    And     Table2.Comments >= Table1.Count
) As CommentBadges
Cross Apply
(
    Select  Count(*) as Count
    From    Table1
    Where   Table1.Action = 'Views'
    And     Table2.Views >= Table1.Count
) As ViewBadges