简体   繁体   中英

Count function in a case statement

I have the following query that counts members:

`SELECT 
distinct count(cst_recno) AS [Member ID],
adr_country AS Country
FROM 
mb_membership
JOIN mb_member_type on mbt_key = mbr_mbt_key
JOIN co_customer ON cst_key=mbr_cst_key and mbr_delete_flag =0 and 
cst_delete_flag=0 
LEFT JOIN co_individual ON cst_key=ind_cst_key and ind_delete_flag=0
LEFT JOIN co_customer_x_customer ON cxc_cst_key_1 = co_customer.cst_key and 
(cxc_end_date is null or datediff(dd,getdate(),cxc_end_date) >=0) and 
cxc_rlt_code='Chapter Member' 
LEFT JOIN co_chapter ON cxc_cst_key_2=chp_cst_key 
LEFT JOIN co_customer_x_address ON cst_cxa_key=cxa_key 
LEFT JOIN co_address ON adr_key=cxa_adr_key 
LEFT JOIN co_country on adr_country=cty_code
LEFT JOIN co_region on rgn_key=cty_rgn_key 
LEFT JOIN vw_client_uli_member_type  WITH (NOLOCK)  ON cst_key=mem_cst_key 
WHERE mbr_join_date >= '7/1/2015' and mbt_code not like '%Council%'
AND ind_int_code <> 'staff' and cst_org_name_dn not like '%urban land ins%' 
and cst_eml_address_dn not like '%@uli.org'
and adr_country ='singapore'
group by adr_country`

and the query returns:

Member ID   Country
145         Singapore

However, I know that it includes a few duplicates because when I take out a count function and don't have a group by clause it returns 140 distinct rows. When I check why it includes a few dupes it is caused by one of the dates. Can you advise? I basically want to run the query that will display 140 distinct count of Member ID:

Member ID   Country
140         Singapore

Instead of SELECT distinct count(cst_recno)... use SELECT count(distinct cst_recno)... :

SELECT 
count(distinct cst_recno) AS [Member ID],
adr_country AS Country
FROM 
mb_membership
JOIN mb_member_type on mbt_key = mbr_mbt_key
JOIN co_customer ON cst_key=mbr_cst_key and mbr_delete_flag =0 and 
cst_delete_flag=0 
LEFT JOIN co_individual ON cst_key=ind_cst_key and ind_delete_flag=0
LEFT JOIN co_customer_x_customer ON cxc_cst_key_1 = co_customer.cst_key and 
(cxc_end_date is null or datediff(dd,getdate(),cxc_end_date) >=0) and 
cxc_rlt_code='Chapter Member' 
LEFT JOIN co_chapter ON cxc_cst_key_2=chp_cst_key 
LEFT JOIN co_customer_x_address ON cst_cxa_key=cxa_key 
LEFT JOIN co_address ON adr_key=cxa_adr_key 
LEFT JOIN co_country on adr_country=cty_code
LEFT JOIN co_region on rgn_key=cty_rgn_key 
LEFT JOIN vw_client_uli_member_type  WITH (NOLOCK)  ON cst_key=mem_cst_key 
WHERE mbr_join_date >= '7/1/2015' and mbt_code not like '%Council%'
AND ind_int_code <> 'staff' and cst_org_name_dn not like '%urban land ins%' 
and cst_eml_address_dn not like '%@uli.org'
and adr_country ='singapore'
group by adr_country`

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