简体   繁体   中英

SQL Distinct Count and Case when

Here is my query for Microsoft SQL Server:

select count(distinct AEN) as Customers  
from 
(   select top 100 ERDAT, AEN,  
    case 
        when AEN = 'MBLE' AND ERDAT between '20220401' and '20220430' then 'Mobile'
        when AEN = 'ISU' AND ERDAT between '20220401' and '20220430' then 'Website'
        when AEN = 'CRM' AND ERDAT between '20220401' and '20220430' then 'CRM'
        when AEN like '_[0-9]%' AND ERDAT between '20220401' and '20220430' then 'ID Number'
        else 'Others'
    end as 'Channels' 
    from [Table]
)

Apparently there is issues with the brackets. Any help is much appreciated! :)

As already mentioned in the comments, you need an alias for your subquery.

change this

count(distinct AEN) as Customers  

into this

count(distinct t.AEN) as Customers  

and also this

    [table]
)

into this

    [table]
) t

look at this DBFiddle

This will run without the error, but I have no clue if this is what you want to achieve, your question is not any clear about that

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