简体   繁体   中英

Trying to count # distinct values of a field based on value of a different field

Looking for some help with my SQL query. I am trying to find a way to specify cases in which a customer purchases or sells at two different stores, but if they purchase at one store and sell at another, I don't care or want that to count.

I have tried this -

Select count(distinct store) OVER(Partition BY Customer)

but it doesn't like the distinct and causes an error. When I dont specify distinct, it will give me the count of all observations of that customer, instead of just the count of # of stores that they purchased from, or sold to.

Based on the data below, customer D is the type im looking to filter for.

My Raw Data:

Customer    Type        Qty     Store
A           Purchase    1       2
A           Purchase    2       2
A           Sale        3       1
B           Sale        24      1
B           Sale        12      1
C           Purchase    4       2
D           Sale        12      2
D           Purchase    4       2
D           Purchase    2       1
D           Purchase    2       1

Any ideas?

Don't you just want to GROUP?

Select Count(store) FROM Blah GROUP BY Customer, Store

Edit: Ah I see what you want - you want a count of store over customer, sorry misread it!

select customer
from your_table
group by customer, type
having count(distinct store) > 1

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