SQL - 仅选择具有多个条目的结果

时间:2011-07-14 22:49:59

标签: sql sql-server-2008

这看起来很简单,但我无法弄清楚如何做到这一点或正确描述相关谷歌它:(

简而言之,有一张表格:

PatientID | Date | Feature_of_Interest...

当他们有兴趣的特征时,我想为多次访问的患者绘制一些结果。没有问题过滤掉感兴趣的功能,但我只希望我的结果查询包含有多个条目的患者。

SELECT PatientID,Date,...
    FROM myTable
    WHERE Feature_Of_Interest is present
    AND (Filter out PatientID's that only appear once)

所以 - 只是不确定如何处理这个问题。我试过了:

WITH X AS (Above SELECT, Count(*),...,Group by PatientID)

然后重新运行查询,但它没有工作。如果需要,我可以发布所有内容,但我得到的印象是我完全落后于此,所以现在推迟。

使用SQL Server 2008.

5 个答案:

答案 0 :(得分:2)

试试这个:

WITH qry AS
(
SELECT a.*,
COUNT(1) OVER(PARTITION BY PatientID) cnt
        FROM myTable  a
 WHERE Feature_Of_Interest = 'present '
)
SELECT *
  FROM qry
WHERE cnt >1

答案 1 :(得分:1)

您可以从访问计数查询开始:

SELECT PatientID, COUNT(*) as numvisits FROM myTable
GROUP BY PatientID HAVING(numvisits > 1);

然后,您可以通过加入来进一步查询此问题。

答案 2 :(得分:1)

您想要加入子查询

JOIN (
    SELECT 
        PatientID
    FROM myTable 
    WHERE Feature_Of_Interest is present 
    GROUP BY PatientID
    HAVING COUNT(*) > 1
) s ON myTable.PatientID = s.PatientID

答案 3 :(得分:0)

当我上床睡觉时快速回答,所以未经测试的代码,但简而言之,您可以使用子查询..

SELECT PatientID,Date,...
    FROM myTable
    WHERE Feature_Of_Interest is present
    AND patientid in (select PatientID, count(patientid) as counter
    FROM myTable
    WHERE Feature_Of_Interest is present group by patientid having counter>1)

我很惊讶你的尝试没有用,它听起来有点像它应该有,除了你没有说计数> 1因此它可能只是归还了它们。

答案 4 :(得分:0)

您应该能够使用与此类似的window function来获得所需内容:

WITH ctePatient AS (
  SELECT PatientID, Date, SUM(1) OVER (PARTITION BY PatientID) Cnt
  FROM tblPatient
  WHERE Feature_Of_Interest = 1
)
SELECT * 
  FROM ctePatient
  WHERE Cnt > 1