简体   繁体   中英

Counting distinct stores SQL

I am fairly new to SQL and was wondering if anyone could help with my code.

I am trying to count the distinct number of stores that are tied to a certain Warehouse which is tied to a purchase order.

Example: If there are 100 stores with this PO that came from Warehouse #2 or #5 or etc... then I would like:

               | COUNT_STORE | WH_LOCATION |
             1 |     100     |     2       |
             2 |     25      |     5       |
             3 |     56      |     1       |

[] My Code:

select count(distinct Store_ID) as Count_Store, WH_Location
from alc_Loc
where alloc_PO = 11345
group by Store_ID, WH_Location

When I run this I get a 1 for "count_store" and it shows me the WH_Location multiple times. I feel as if something is not tying in correctly.

Any help is appreciated!

Just remove store_id from the group by :

select count(distinct Store_ID) as Count_Store, WH_Location
from alc_Loc
where alloc_PO = 11345
group by WH_Location;

When you include Store_ID in the group by , you are getting a separate row for each Store_ID . The distinct count is then obviously 1 (or 0 if the store id is NULL ).

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