SQL:计算具有多个条件的不同列组合

SQL: Count distinct column combinations with multiple conditions

我有一个看起来像这样的连接 table,其中 mytable 包含日期、storeid、项目和单位,而 stores 有 state 和 storeid。

date         state      storeid   item   units
==============================================
2020-01-22   new york   712       a      5
2020-01-22   new york   712       b      7
2020-02-18   new york   712       c      0
2020-05-11   new york   518       b      9
2020-01-22   new york   518       b      10
2020-01-21   oregon     613       b      0
2020-02-13   oregon     613       b      9
2020-04-30   oregon     613       b      10
2020-01-22   oregon     515       c      3

我正在尝试创建一个列来计算 storeiditem 在一行中出现的唯一次数date 在给定的日期范围内并且 units 大于 0。另外,只需要 select/group by state 和计算列。我有一些看起来像这样的东西:

select
    s.state,
    count(distinct case
        when m.date between '2020-01-01' and '2020-03-31'
        and m.units > 0
        then m.storeid, m.item
    end) as q1_total
    from mytable as m
        left join (select
            state,
            storeid
        from stores) s
        on m.storeid=s.storeid
group by s.state

我知道我的计数函数写得不正确,但我不确定如何修复它。试图让最终结果看起来像这样。

state         q1total 
=========================
new york      3
oregon        2

使用此查询:

select distinct state, storeid, item
from mytable
where date between '2020-01-01' and '2020-03-31' and units > 0

根据您的条件,您将获得状态、商店 ID 和项目的所有不同组合,您可以对其进行聚合:

select state, count(*) q1total
from (
  select distinct state, storeid, item
  from mytable
  where date between '2020-01-01' and '2020-03-31' and units > 0
) t
group by state

参见demo
结果:

> state    | q1total
> :------- | ------:
> new york |       3
> oregon   |       2