简体   繁体   中英

SQL: Count distinct column combinations with multiple conditions

I have a joined table that looks like this where mytable contains date, storeid, item and units, whereas stores has state and 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

And I am trying to create a column that counts the unique number of times that both storeid and item occur in a row where the date is between a given date range and units is greater than 0. Also, only need to select/group by state and the calculated column. I have something that looks like this:

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

I know my count function isn't written correctly, but I'm not sure how to fix it. Trying to get the end result to look like this.

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

With this query:

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

you get all the distinct combinations of state, storeid and item under your conditions and you can aggregate on it:

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

See the demo .
Results:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM