Sql 在属性为两个键中的任意一个键的情况下,计数不同

Sql 在属性为两个键中的任意一个键的情况下,计数不同,sql,postgresql,Sql,Postgresql,鉴于此表: create temp table stats ( name text, country text, age integer ) insert into stats values ('eric', 'se', 1), ('eric', 'dk', 4), ('johan', 'dk', 6), ('johan', 'uk', 7), ('johan', 'de', 3), ('dan', 'de', 3), ('dan', 'de

鉴于此表:

create temp table stats (
name text, country text, age integer
)

insert into stats values 

('eric',    'se',   1),
('eric',    'dk',   4),
('johan',   'dk',   6),
('johan',   'uk',   7),
('johan',   'de',   3),
('dan', 'de',   3),
('dan', 'de',   3),
('dan', 'de',   4)
我想知道国家或年龄与钥匙相同的不同姓名的计数

country age count
se      1   1
de      3   2
de      4   3
dk      4   3
dk      6   2
uk      7   1
有3个不同的名字,分别是
country=dk
(埃里克,约翰)或
age=4
(埃里克,丹)

所以我的问题是,写这个查询的最佳方式是什么

我有这个解决方案,但我发现它非常丑陋

with country as (
 select count(distinct name), country
 from stats
 group by country
),
age as (
 select count(distinct name), age
 from stats
 group by age
),
country_and_age as(
 select count(distinct name), age, country
 from stats
 group by age, country
)
select country, age, c.count+a.count-ca.count as count from country_and_age ca join age a using(age) join country c using(country)

有更好的方法吗?

从统计数据中选择不同的年龄和国家。对于每个记录,计算您在匹配国家或年龄的记录中找到的不同名称的数量

select
  country, 
  age,
  (
    select count(distinct name)
    from stats s 
    where s.country = t.country 
    or s.age = t.age
  ) as cnt
from (select distinct country, age from stats) t;

我个人不喜欢在线查询,所以我会这样做:

SELECT DISTINCT
        *
FROM    ( SELECT    country ,
                    age ,
                    COUNT(*) OVER ( PARTITION BY country ) AS c_cnt ,
                    COUNT(*) OVER ( PARTITION BY age ) AS a_cnt
          FROM      stats
        ) a
WHERE   c_cnt > 0
        OR a_cnt > 0

我不确定Postgres的性能,但在SQL Server中,“在线”速度要慢约3倍(73%对27%)

您也可以加入原始表:

SELECT
  s1.country,
  s1.age,
  COUNT(distinct s2.name)
FROM stats s1
JOIN stats s2 ON s1.country=s2.country OR s1.age=s2.age
GROUP by 1, 2;

你把事情弄得太复杂了。首先编写一个满足条件的查询,即查找所有国家或年龄与关键字相同的行。完成后,添加聚合函数。我不知道满足条件的查询,当我知道时,我没有时间遍历所有行。我需要尽可能多地进行预计算。这确实好得多,我从来没有在变量列表中处理过这样的子查询。很酷的解决方案!