首页 > 解决方案 > 避免 SELECT 重复行上的 CASE

问题描述

新手在这里,我正在努力修复一个查询,其中选择案例由于聚合而在结果中创建重复行。

select distinct A, B, C, sum(case when X = 1 then N end) as D, sum(case when X = 2 then N end) as E
from table1
where X in (1,2)
group by A, B, C

结果

A     B    C    D    E
205  NICE  Y   752    
205  NICE  Y         4356

预期的

A     B    C    D    E
205  NICE  Y   752   4356

标签: sqlamazon-redshift

解决方案


这应该做你想要的:

select A, B, C,
       sum(case when X = 1 then N end) as D,
       sum(case when X = 2 then N end) as E
from table1
where X in (1, 2)
group by A, B, C;

select distinct不需要。

如果您获得多行,则 、 和 的值AB完全相同C。这可能是由于值中的空格、隐藏字符、在不同字符集中看起来相同的字符。

我建议您独立调查每一列:

select distinct A
from table1;

找出差异在哪里。


推荐阅读