SQL查询仅在多次出现时才显示两个表中的项目

时间:2014-11-30 19:27:08

标签: sql sql-server

我有2张表,证据和嫌疑人。

在我的Evidence表中,我现在只关注Hash列和SuspectID列。 感兴趣的可疑表列是SuspectID,SuspectFirstName,SuspectLastName和Suspect.SuspectState。

我想在Evidence.Hash和Suspect.SuspectID之间建立联系。我希望能够显示与特定证据文件关联的所有嫌疑人。即:

“文件[文件的哈希]连接到Suspect1,Suspect2和Suspect3” “文件[文件2的哈希]连接到Suspect1,而Suspect2”

我想仅在证据文件连接到多个嫌疑人时才建立这些连接。

这是我到目前为止所拥有的。什么都没有完全奏效:

这将打印出连接有多个可疑ID的文件哈希值。我还需要包括可疑的名字和州。

SELECT Evidence.Hash 
FROM Evidence 
GROUP BY Evidence.Hash 
HAVING COUNT(Evidence.SuspectID) > 2

这将返回所有哈希值,其中所有嫌疑人都按哈希排序。这没关系,但我宁愿不把它们列出来。

SELECT Evidence.Hash, Evidence.SuspectID, SuspectFirstName, Suspect.SuspectLastName
FROM Evidence
INNER JOIN Suspect 
ON Evidence.SuspectID=Suspect.SuspectID 
ORDER BY Evidence.Hash

我想结合两个查询。我尝试了以下但现在没有任何东西打印到屏幕上。

SELECT Evidence.Hash, Evidence.SuspectID, SuspectFirstName, Suspect.SuspectLastName
AS FileHash  
FROM Evidence
INNER JOIN Suspect
ON Suspect.SuspectID = Evidence.SuspectID
GROUP BY Evidence.Hash,Evidence.SuspectID, SuspectFirstName, Suspect.SuspectLastName
HAVING Count(Evidence.SuspectID )> 1 

如果有人可以帮助我并告诉我如何获得连接到超过1个suspectID的哈希值,我将不胜感激。

3 个答案:

答案 0 :(得分:0)

未经测试,应该正常工作。

SELECT 
    Evidence.Hash AS FileHash, 
    Evidence.SuspectID, 
    Suspect.SuspectFirstName, 
    Suspect.SuspectLastName   
FROM 
    Evidence
    INNER JOIN Suspect ON Suspect.SuspectID = Evidence.SuspectID
GROUP BY 
    Evidence.SuspectID
HAVING 
    COUNT(Evidence.SuspectID )> 1 

更新:如果我正确理解了这个问题,GROUP列应该是Suspect.SuspectID

GROUP BY 
    Suspect.SuspectID
HAVING 
    COUNT(Suspect.SuspectID )> 1 

答案 1 :(得分:0)

你需要

  • 获取哈希,其中有多个嫌疑人,然后
  • 加入详情。

尝试

SELECT
  MS.hash FileHash
  , E.SuspectID
  , S.SuspectFirstName
  , S.SuspectLastName
FROM (
  SELECT
    E.hash
  FROM Evidence E
  JOIN Suspect S
    ON E.SuspectID = S.id
  GROUP BY E.hash
  HAVING COUNT(E.SuspectID) > 1) MS
JOIN Evidence E
  ON MS.hash = E.hash
JOIN Suspect S
  ON E.SuspectID = S.id
;

可能有其他选择 - 但现在无法对它们进行测试。

答案 2 :(得分:0)

使用window function查找Evidence.Hash表格中多次出现的Evidence

;with cte as
(
SELECT row_number() over (partition by Hash order by SuspectID) Rn, *
FROM Evidence 
)
select * from cte where rn>1

现在将结果加入Suspect

;with cte as
(
SELECT row_number() over (partition by Hash order by SuspectID) Rn, *
FROM Evidence 
)
select Evidence.Hash, Evidence.SuspectID, SuspectFirstName, Suspect.SuspectLastName
  from cte Evidence 
  join Suspect
    on Evidence.SuspectID=Suspect.SuspectID
where rn>1