简体   繁体   中英

SQL Server - Compare on multiple columns in differnet rows within same table

I have a table that holds the values read from 2 meters:

----------------------------
   Date   | MeterID | Value
----------------------------
  1/2/14       A       1.3
  2/2/14       A       1.8
  2/2/14       B       3.8
  3/3/14       A       1.2
  4/3/14       A       1.8
  4/3/14       B       2.9

I need a query that will count the number of days that a reading exists for BOTH meter types ( A & B )?
In the example above this should yield 2 as the result.

Thanks.

You can use a temporary table to list [Date] s when there were occurrences in MeterID for both A and B and then COUNT() all this [Date] s :

SELECT COUNT(t.*) 
FROM ( SELECT [Date] 
       FROM [table] 
       GROUP BY [Date] 
       HAVING COUNT(DISTINCT [MeterID]) = 2
     ) t

Another solution, using sets:

select count(*) from
(
    select distinct date from table where meterid='A'
    intersect
    select distinct date from table where meterid='B'
) x

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM