我有如下所示的資料集:
UserID AccountID CloseDate
1 1000 14/3/2022
1 2000 16/3/2022
2 1000 NULL
2 2000 4/3/2022
2 3000 NULL
我想檢查一個 user_id 內的所有關閉日期是否不為空。換句話說,如果 user_id 中的所有帳戶都已關閉。我正在嘗試使用 MAX 或 MIN 但它沒有按預期作業,因為它只是避免使用 NULL 值。還有其他功能可以檢查嗎?假設我的輸出將是另一列,當所有 CloseDates 不為空時分配 1,否則為 0。
樣本輸出:
UserID AccountID CloseDate Check
1 1000 14/3/2022 1
1 2000 16/3/2022 1
2 1000 NULL 0
2 2000 4/3/2022 0
2 3000 NULL 0
uj5u.com熱心網友回復:
使用條件聚合明確COUNT列具有值的行NULL:
SELECT GroupedColumn,
COUNT(CASE WHEN NullableColumn IS NULL THEN 1 END) AS NullCount
FROM dbo.YourTable
GROUP BY GroupedColumn;
如果您只想擁有一個1或0只是將計數包裝在一個CASE運算式中:
CASE COUNT(CASE WHEN NullableColumn IS NULL THEN 1 END) WHEN 0 THEN 1 ELSE 0 END
uj5u.com熱心網友回復:
您可以嘗試使用FIRST_VALUE條件視窗功能
SELECT *,
FIRST_VALUE(IIF(CloseDate IS NULL,0,1)) OVER(PARTITION BY UserID ORDER BY CloseDate )
FROM T
sqlfiddle
uj5u.com熱心網友回復:
with dataset as (select 1 as UserId, 1000 as AccountID, '14/3/2022' as CloseDate
union all select 1, 2000, '16/3/2022'
union all select 2, 1000, NULL
union all select 2, 2000, '4/3/2022'
union all select 2, 3000, NULL)
select userid from dataset
group by userid
having sum(case when closedate is null then 1 else 0 end) = 0;
uj5u.com熱心網友回復:
select d.*, iif(chk>0, 0, 1) chk
from d
outer apply (
select UserId, COUNT(*) CHK
from d dd
WHERE d.UserId = dd.UserId
and dd.CloseDate IS NULL
group by UserId
) C
uj5u.com熱心網友回復:
您也可以使用“存在”。例如:
select y.UserID, y.AccountID, y.CloseDate,
-- [Check]: returns 0 if there is a row in the table for the
-- UserID where CloseDate is null, else 1
(case when exists(select * from YourTable y2 where y2.UserID = y.UserID
AND y2.CloseDate is null) then 0 else 1 end) as [Check]
from YourTable y
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/446854.html
上一篇:將字串中的逗號分隔值與表匹配
