确定值大于 0 的列数

Determining the count of columns with a value greater than 0

好的guys/gals...

这是我的结果集:

这是我想要的最终结果集

为了达到这个结果,我目前正在使用 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

然后我得到...

...这里我改变了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

...最后,如果我将 ors 更改为 ands,我会得到零结果...

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

只需在查询中使用一些 CASE 语句

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

祝你有愉快的一天!