确定值大于0的列数

时间:2018-09-26 01:09:16

标签: tsql subquery aggregate common-table-expression having

好家伙/女友...

这是我的结果集:

enter image description here

这是我想要的最终结果集

enter image description here

要获得结果,我目前正在使用 n (3)子查询...这并不理想...

declare @userId int = 436
select
    (select count(PRODUCT_ID) from sl_suggested_asset where PRODUCT_ID > 0 and user_id = @userId) As 'PRODUCT_ID',
    (select count(DIGI_DOC_ID) from sl_suggested_asset where DIGI_DOC_ID > 0 and user_id = @userId) As 'DIGI_DOC_ID',
    (select count(QR_CODE_ID) from sl_suggested_asset where qr_code_id > 0  and user_id = @userId) As 'QR_CODE_ID'

我想使用cteaggregate ...

这就是我的想法...

select count(product_id), count(DIGI_DOC_ID), count(qr_code_id), user_id
from sl_suggested_asset
where user_id = 436
group by user_id

但这给了我行的总数...

因此应该使用我的having子句,但这意味着我需要拥有正确的group by predicate ...这就是我遇到的问题...

下面是我尝试过的一些示例...

select 
    count(PRODUCT_ID) As 'PRODUCT_ID'
    , count(DIGI_DOC_ID) As 'DIGI_DOC_ID'
    , count(QR_CODE_ID) As 'QR_CODE_ID'
    , user_id
from sl_suggested_asset
where 
    PRODUCT_ID > 0
or
    DIGI_DOC_ID > 0
or
    QR_CODE_ID > 0
and
    user_id = 436
group by user_id

然后我得到...

enter image description here

...在这里,我更改了where子句条件的顺序...

select 
    count(PRODUCT_ID) As 'PRODUCT_ID'
    , count(DIGI_DOC_ID) As 'DIGI_DOC_ID'
    , count(QR_CODE_ID) As 'QR_CODE_ID'
    , user_id
from sl_suggested_asset
where 
    user_id = 436
and
    PRODUCT_ID > 0
or
    DIGI_DOC_ID > 0
or
    QR_CODE_ID > 0  
group by user_id

...我得到与上述相同的结果...

...现在我将where子句更改为= 0并得到相同的结果,这意味着where子句被完全忽略了...

select 
    count(PRODUCT_ID) As 'PRODUCT_ID'
    , count(DIGI_DOC_ID) As 'DIGI_DOC_ID'
    , count(QR_CODE_ID) As 'QR_CODE_ID'
    , user_id
from sl_suggested_asset
where 
    user_id = 436
and
    PRODUCT_ID = 0
or
    DIGI_DOC_ID = 0
or
    QR_CODE_ID = 0  
group by user_id

enter image description here

...最后,如果我将or更改为and,则结果为零...

select 
    count(PRODUCT_ID) As 'PRODUCT_ID'
    , count(DIGI_DOC_ID) As 'DIGI_DOC_ID'
    , count(QR_CODE_ID) As 'QR_CODE_ID'
    , user_id
from sl_suggested_asset
where 
    user_id = 436
and
    PRODUCT_ID = 0
and
    DIGI_DOC_ID = 0
and
    QR_CODE_ID = 0  
group by user_id

enter image description here

1 个答案:

答案 0 :(得分:2)

只需在查询中使用一些CASE STATEMENTS

SELECT SUM( CASE WHEN PRODUCT_ID > 0 THEN 1 ELSE 0 END ) as PRODUCT_ID , SUM( CASE WHEN DIGI_DOC_ID>0 THEN 1 ELSE 0 END ) as DIGI_DOC_ID, SUM( CASE WHEN QR_CODE_ID>0 THEN 1 ELSE 0 END ) as QR_CODE_ID FROM sl_SUGGESTED_ASSET WHERE USER_ID =436

祝你有美好的一天!