I have a table of store information describing which stores are linked with one another. The data might look like this:
| store_id | link_num | linked_store | | 1 | 1 | 10 | | 1 | 1 | 10 | | 1 | 2 | 11 | | 1 | 3 | 12 | | 1 | 3 | 13 | | 1 | 4 | 14 |
I want to check if there is a store linked to different stores AT THE SAME link_num. Is it possible to have a query that will output something like below?
| store_id | link_num | count | check | | 1 | 1 | 2 | same | | 1 | 2 | 1 | (null) | | 1 | 3 | 2 | diff | | 1 | 4 | 1 | (null) |
Any help is appreciated. Thank you
Advertisement
Answer
You can use count(distinct ..)
for this:
select store_id, link_num, count(*) as count, case when count(distinct linked_store) = 1 and count(*) > 1 then 'same' when count(distinct linked_store) > 1 and count(*) > 1 then 'diff' end as "check" from the_table group by store_id, link_num;