如何在SQL Server中检查多个Column值的存在

时间:2016-05-10 14:20:51

标签: sql-server query-optimization

我有一张表Yearly_Author_CoAthors,结构如下:

Author  |  CoAuthor  |   Year  
------------------------------
677     |  901706    |   2005
677     |  38459     |   2007
677     |  901706    |   2007
677     |  1695352   |   2007
677     |  901706    |   2009
677     |  372089    |   2011
677     |  403400    |   2011
677     |  478885    |   2011
677     |  478885    |   2012
677     |  42700     |   2013
677     |  625964    |   2013
1359    |  133112    |   2005
1359    |  1412785   |   2005
1359    |  151268    |   2006
1359    |  232222    |   2007
1359    |  264864    |   2007  
...  
...  

我执行了一个查询:

SELECT * FROM Yearly_Author_CoAuthors
WHERE CoAuthor = 901706  

它输出为:

Author  |  CoAuthor  |  Year
----------------------------
677     |  901706    |  2005
677     |  901706    |  2007
677     |  901706    |  2009
1683703 |  901706    |  2012  

这意味着CoAuthor = 901706与超过1 Author相关联,即677和1683703.

所以问题是:
如何修改此查询以检查与超过1 CoAuthor相关联的所有此类Author

3 个答案:

答案 0 :(得分:1)

使用来自Arulkumar的想法,此查询给出了预期的结果。

SELECT   CoAuthor, COUNT(DISTINCT Author) [AuthorCount], Year
FROM     Yearly_Author_CoAuthors
GROUP BY Year, CoAuthor
HAVING   COUNT(DISTINCT Author) > 1
ORDER BY CoAuthor, Year

答案 1 :(得分:0)

将您的给定查询视为子查询,根据您可以应用GROUP BY作者列的结果,然后检查HAVING COUNT(Author) > 1

它会给出您期望的结果:

SELECT Author, COUNT(Author) AuthorCount
FROM (
    SELECT Author, CoAuthor, [Year]
    FROM Yearly_Author_CoAuthors
    WHERE CoAuthor = 901706
) AC
GROUP BY Author
HAVING COUNT(Author) > 1

答案 2 :(得分:0)

由于在评论中写这篇文章有点太多了,我会把它放在这里,但实际上4小时前@maliks的回答几乎也是如此。

我已经更改了示例数据的最后两行,以便从中获得一些结果。

IF OBJECT_ID('t_test') IS NOT NULL DROP TABLE t_test
GO
CREATE TABLE t_test (Author int NOT NULL, CoAuthor int NOT NULL, Year int NOT NULL)
GO
INSERT t_test (Author, CoAuthor , Year)

SELECT 677     ,  901706    ,   2005 UNION ALL
SELECT 677     ,  38459     ,   2007 UNION ALL
SELECT 677     ,  901706    ,   2007 UNION ALL
SELECT 677     ,  1695352   ,   2007 UNION ALL
SELECT 677     ,  901706    ,   2009 UNION ALL
SELECT 677     ,  372089    ,   2011 UNION ALL
SELECT 677     ,  403400    ,   2011 UNION ALL
SELECT 677     ,  478885    ,   2011 UNION ALL
SELECT 677     ,  478885    ,   2012 UNION ALL
SELECT 677     ,  42700     ,   2013 UNION ALL
SELECT 677     ,  625964    ,   2013 UNION ALL
SELECT 1359    ,  133112    ,   2005 UNION ALL
SELECT 1359    ,  1412785   ,   2005 UNION ALL
SELECT 1359    ,  151268    ,   2006 UNION ALL
SELECT 1359    ,  901706    ,   2005 UNION ALL
SELECT 1359    ,  901706    ,   2007

GO

SELECT Year, CoAuthor, COUNT(DISTINCT Author)
  FROM t_test
 GROUP BY Year, CoAuthor
 HAVING COUNT(DISTINCT Author) > 1