sql查询输出具有一条记录的行,另一条查询输出多条记录的行

时间:2016-03-15 11:59:53

标签: sql

我正在处理两个问题:

  1. 根据Barcode FROM Sputum_Collection输出只有一条记录的行。
  2. 输出具有多条记录的行。
  3. Sputum_Collection

    Barcode | ID | SputumNo | Volume | Collect_Date
    201003 | NCL37M | S1    | Yes   | 03/15/16
    201003 | NCL37M | S3    |Yes    | 03/16/16
    201002 | PCL75F | S1    | Yes   | 03/14/16
    201001  |MCL29M | S1    |Yes    |03/14/16
    201003  |NCL37M | S2    |Yes    |03/16/16
    201004  |LKM23M | S1    |Yes    |03/16/16
    

    输出1:

    Barcode | ID | SputumNo | Volume | Collect_Date
    201001  |MCL29M | S1    |Yes    |03/14/16
    201004  |LKM23M | S1    |Yes    |03/16/16
    

    2的输出:

    Barcode | ID | SputumNo | Volume | Collect_Date
    201003 | NCL37M | S1    | Yes   | 03/15/16
    201003 | NCL37M | S3    |Yes    | 03/16/16
    201002 | PCL75F | S1    | Yes   | 03/14/16
    201003  |NCL37M | S2    |Yes    |03/16/16
    

3 个答案:

答案 0 :(得分:1)

您可以使用嵌套选择根据条形码对数据进行分组,并使用HAVING语句在组中添加条件。

查询1

select * from Sputum_Collection
where Barcode in
(
select Barcode from Sputum_Collection
group by barcode
having count(*) = 1
)

查询2

select * from Sputum_Collection
where Barcode in
(
select Barcode from Sputum_Collection
group by barcode
having count(*) > 1
)

答案 1 :(得分:0)

1,试试这个

select Barcode, ID, SputumNo, Volume, Collect_date
from
(
    select Barcode, ID, SputumNo, Volume, Collect_date,
           Count(Barcode) over(partition by Barcode) as Count
)
where Count = 1;

和2,你知道该怎么做......

答案 2 :(得分:0)

查询#1:

SELECT 
    a.* 
FROM 
    imt_database.test a 
LEFT JOIN
    (SELECT 
         Barcode, COUNT(ID) as ct 
     FROM 
         imt_database.test 
     GROUP BY 
         id) tmp ON tmp.Barcode = a.Barcode 
WHERE 
    ct =1

查询#2:

SELECT 
    a.* 
FROM 
    imt_database.test a 
LEFT JOIN
    (SELECT 
         Barcode, COUNT(ID) as ct 
     FROM 
         imt_database.test 
     GROUP BY
         id) tmp ON tmp.Barcode = a.Barcode 
WHERE 
    ct > 1

取决于您的DBMS