SQL:查找值出现多次的位置

时间:2015-07-08 15:28:15

标签: sql sql-server

我试图找到" subfield a"不止一次出现。

此查询非常适合查找具有任何子字段a的行:

SELECT Distinct 
    BT.BibliographicRecordID as recordid
FROM 
    BibliographicTags BT with (nolock)
JOIN 
    BibliographicSubfields BS with (nolock) ON BS.BibliographicTagID = BT.BibliographicTagID
WHERE 
    BT.TagNumber = 049
    AND BS.subfield ='a' 

但我正在尝试以下效果:

SELECT Distinct 
    BT.BibliographicRecordID as recordid
FROM 
    BibliographicTags BT with (nolock)
JOIN 
    BibliographicSubfields BS with (nolock) ON BS.BibliographicTagID = BT.BibliographicTagID
WHERE 
    BT.TagNumber = 049
    AND BS.subfield = 'a' APPEARS MORE THAN ONCE

谢谢!

1 个答案:

答案 0 :(得分:1)

Maybe a simple GROUP BY and HAVING clause does the trick?

SELECT BT.BibliographicRecordID as recordid
FROM BibliographicTags BT with (nolock)
JOIN BibliographicSubfields BS with (nolock)
ON BS.BibliographicTagID = BT.BibliographicTagID
AND BS.subfield ='a'
WHERE BT.TagNumber = 049
GROUP BY BT.BibliographicRecordID
HAVING COUNT(*) > 1

BTW, make sure you have a very good reason to use the with (nolock) hints. It's generally not what you want.

Relevant: SQL Server NOLOCK Hint & other poor ideas.

EDIT:

Actually, without fully understanding your data model, the following query is more likely to give you the data as you expect:

SELECT Distinct BT.BibliographicRecordID as recordid
  FROM BibliographicTags BT
 WHERE BT.BibliographicTagID IN (
                SELECT BT.BibliographicTagID
                  FROM BibliographicTags BT
                  JOIN BibliographicSubfields BS
                    ON BS.BibliographicTagID = BT.BibliographicTagID
                   AND BS.subfield = 'a'
                 GROUP BY BT.BibliographicTagID
                HAVING COUNT(*) > 1)

EDIT 2

Here is the SQL Fiddle link to see the query in action. Hopefully you'll be able to spot what is different about your query? You are using SQL Server, right?

相关问题