我在下面有一些示例记录。我有兴趣统计ID记录中只有X值的地方。例如,我需要计算ID = 10720和11120,因为两者都只有X值。如果它们具有X和其他类似XY或AB的值,例如ID = 10586,我将不计算在内。
当前,我正在SQL和电子表格中使用这两个步骤来获取我的结果,但效率不高。
ID LocationCode Dates
10720 VA X 3/20/2012 1:00:00 PM
10586 DC X 7/12/2003 7:00:00 AM
10586 DC X 8/2/2003 4:44:25 AM
10586 DC XY 2/21/2019 8:00:00 AM
10892 NY X 5/3/2009 4:00:00 PM
10892 NY X 5/5/2009 6:30:00 AM
10892 NY X 5/7/2009 11:45:00 AM
10892 CA AB 4/5/2016 8:40:00 AM
10932 CA AB 8/3/2009 4:00:00 AM
10932 CA AB 8/11/2009 5:30:00 PM
10932 CA X 5/8/2010 4:00:00 AM
11120 FL X 11/25/2010 10:27:00 AM
11120 FL X 12/8/2010 9:02:00 PM
11120 FL X 12/28/2010 10:30:00 AM
步骤1:
select
location,
string_agg(code, '') as CODE,
count(distinct ID) as count
from TEMP
group by location
步骤2:将结果存入电子表格并过滤出唯一的X值。
SQL Server中是否可以直接产生结果?
答案 0 :(得分:1)
只需:
select count(distinct id)
from t
where not exists (select 1 from t t2 where t2.id = t.id and t2.code <> 'X');
或者,如果愿意,可以分为两个层次:
select count(*)
from (select id
from t
group by id
having min(code) = max(code) and min(code) = 'X'
) x;
答案 1 :(得分:1)
另一种方式:
select count(*)
from
(
select id table where code = 'X'
EXCEPT
select id from where code != 'X'
) tmp
答案 2 :(得分:0)
一种可能的解决方案:
select ID
from TEMP
where Code = 'X'
group by ID
having count(distinct Code) = 1
答案 3 :(得分:0)
对结果求和将得出'X'的总数。
类似
select code, sum(count) as count
from (
select
location,
string_agg(code, '') as CODE,
count(distinct ID) as count
from TEMP
group by location
) codes_aggregated
group by code
having code = 'X'