用于获取两个用户未评级的项目的SQL查询

时间:2016-01-14 17:29:40

标签: sql sql-server select

说我有下表:

+------------+------+--------+
| reviewerID | item | rating |
+------------+------+--------+
|          1 |    1 |       5|
|          1 |    2 |       5|
|          1 |    3 |       5|
|          2 |    4 |       5|
|          2 |    1 |       5|
|          2 |    2 |       5|
+------------+------+--------+

我希望得到评论者1未评级但被评论者2评价的项目,反之亦然。输出应该是这样的:

+------------+------+--------+
| reviewerID | item | rating |
+------------+------+--------+
|          1 |    3 |       5|
|          2 |    4 |       5|
+------------+------+--------+

2 个答案:

答案 0 :(得分:1)

您可以计算这些项目的评论者数量(在这两位评论者之间),并且只选择一位评论者:

SELECT *
FROM   mytable
WHERE  item IN (SELECT   item
                FROM     mytable
                WHERE    reviewerID IN (1, 2)
                GROUP BY item
                HAVING   COUNT(*) = 1)

答案 1 :(得分:0)

这就是你所需要的,以获得理想的结果......

SELECT a.* FROM Reviewer a  
JOIN (  SELECT DISTINCT item FROM Reviewer
        GROUP BY item
        HAVING count(item) < 2) b  
ON a.item = b.item  

希望它有所帮助!! 祝你好运!!