返回同一表中匹配行和不匹配行的SQL查询
我有一个表,希望执行SQL查询以返回Postgres中的匹配行和不匹配行。如果SQL也适用于Informix,那就太好了,但这不是必需的返回同一表中匹配行和不匹配行的SQL查询,sql,postgresql,Sql,Postgresql,我有一个表,希望执行SQL查询以返回Postgres中的匹配行和不匹配行。如果SQL也适用于Informix,那就太好了,但这不是必需的 create temp table t1 (cust integer, product char(16), qty numeric(16,2)); insert into t1 values(1000, 11, 100); insert into t1 values(1000, 11, 200); insert into t1 values(1000, 22
create temp table t1 (cust integer, product char(16), qty numeric(16,2));
insert into t1 values(1000, 11, 100);
insert into t1 values(1000, 11, 200);
insert into t1 values(1000, 22, 300);
insert into t1 values(1001, 22, 400);
insert into t1 values(1002, 33, 500);
insert into t1 values(1003, 44, 600);
insert into t1 values(1004, 55, 700);
insert into t1 values(1004, 55, 800);
select cust,
product,
sum(qty)
from t1
where product = '11'
group by 1,2
union all
select cust,
null,
null
from t1
where product != '11'
and cust not in (select cust from t1 where product = '11')
order by cust;
客户积和
------+------------------+--------
1000 | 11 | 300.00
1001 | |
1002 | |
1003 | |
1004 | |
1004 | |
我希望cust等于指定产品的所有行,但我也希望所有cust编号都返回null,表示没有产品的产品和数量。我有两个问题。列cust应该是唯一的,cust 1004返回了两个重复的行,如果我在查询中使用distinct,它会在qty字段中给出一个关于数据类型的错误。第二个问题是,当针对较大的数据集(如10000行)运行此SQL时,需要很长时间。您可以尝试使用聚合筛选器,例如:
select cust, product, sum( case when product = '11' then qty else 0 end) sum
from t1
group by 1,2
order by cust
您可以使用
filter()
子句使用条件聚合:
select t1.cust,
max(t1.product) filter (where t1.product = '11') as product,
sum(t1.qty) filter (where t1.product = '11')
from t1
group by t1.cust, t1.product
order by t1.cust, t1.product
max(t1.product).
也可以写成case,当t1.product='11'时,则t1.product else null结束为product
,并且仅用于隐藏实际的产品编号。如果您不介意查看产品编号,那么您可以简单地使用t1。product
there也可以指定预期结果。不相关,但是: