在一个查询中分别为两个不同的日期生成两个 SUM 值列

Generate two SUM value columns for two different dates separately in one query

我正在尝试合并两个查询

  select s.id , sum(h.val)  as [VAL]
    from identity s inner join price_net h on s.date = h.date and s.num_id = h.num_id and s.rec_type = h.rec_type
    where s.date = '10/25/21'
    and s.rec_type = 'D'
    and s.tier = 'P'
    group by s.

.

select s.id , sum(h.val)  as [VAL]
        from identity s inner join price_net h on s.date = h.date and s.num_id = h.num_id and s.rec_type = h.rec_type
        where s.date = '10/26/21'
        and s.rec_type = 'D'
        and s.tier = 'P'
        group by s.

,我想要它,所以有一个 table,其中一列用于 s.id,下一列是每个日期的 VAL 列。如果某个值在特定日期无法用于给定 s.id,则应显示 NA。

我想您正在寻找条件聚合(CASE WHEN 在聚合函数中)。

select
  i.id,
  sum(case when i.date = date '2021-10-25' then pn.val end) as val_20211025,
  sum(case when i.date = date '2021-10-26' then pn.val end) as val_20211026
from identity i
join price_net pn on pn.date = i.date 
                 and pn.num_id = i.num_id
                 and pn.rec_type = i.rec_type
where i.tier = 'P'
and i.rec_type = 'D'
and i.date in (date '2021-10-25', date '2021-10-26')
group by i.id
order by i.id;

对于两个条件,您都可以使用 case when

select s.id , sum(CASE WHEN s.date = '10/25/21' THEN h.val eLSE  O END)  as [VAL]
, sum(CASE WHEN s.date = '10/26/21' THEN h.val eLSE  O END)  as [VAL2]
        from identity s inner join price_net h on s.date = h.date and s.num_id = h.num_id and s.rec_type = h.rec_type
        where 
        as.rec_type = 'D'
        and s.tier = 'P'
        group by s.ìd