我如何解决此要求。请帮忙。
客户表 - CT
ClientID Balance
123 10
123 20
123 30
123 40
124 50
124 60
124 Null
我想从CT表中找到最大值(平衡值) 条件 - >如果没有空值,那么我必须找出max(Balance)否则它应该是Null。见下面的结果,我期待。
ClientID Balance
123 40
124 Null
我写的查询如下。但还有更有活力的方法吗?
Select ClientID,
CASE WHEN MIN(Balance) = NULL THEN
NULL
ELSE
MAX(Balance) END AS 'MaxBalance'
From CT
Group by clientID
请让我知道,还有其他选择吗?
答案 0 :(得分:2)
试试这个:
Select ClientID,
(CASE WHEN count(balance) < count(*)
THEN NULL
ELSE MAX(Balance)
END) AS MaxBalance
From CT
Group by clientID
或者,更多的是cumbsersome,但也许更清楚:
Select ClientID,
(CASE WHEN sum(case when balance is null then 1 else 0 end) > 0
THEN NULL
ELSE MAX(Balance)
END) AS MaxBalance
From CT
Group by clientID
答案 1 :(得分:1)
怎么样:
SELECT clientid
, balance
FROM
(
SELECT clientid
, balance
, row_number()
over( partition by clientid
order by CASE WHEN balance IS NULL THEN 0 ELSE 1 END
, balance DESC
) r
FROM ct
) n
WHERE r = 1
答案 2 :(得分:1)
我不确定[Balance]的数据类型是什么,但如果是int,则可以执行以下操作:
Select ClientID, NULLIF(MAX(ISNULL(Balance,2147483647)),2147483647)
From CT
GROUP BY ClientID
如果[Balance]不是int,只需将2147483647
替换为该数据类型的最大值。
当然,如果你确实拥有余额为2147483647的客户,则存在危险。在这种情况下,他们的最大余额将显示为空。
答案 3 :(得分:0)
这适用于SQL 2005 +
; WITH a AS (
SELECT DISTINCT ClientID
FROM CT
WHERE Balance IS NULL )
SELECT t.ClientID, MAX(t.Balance) "MaxBalance"
FROM CT t
LEFT JOIN a ON t.CLientID = a.ClientID
WHERE a.ClientID IS NULL
GROUP BY t.CLientID
UNION ALL
SELECT a.ClientID, NULL
FROM a
答案 4 :(得分:0)
这可行,但不是很优雅:
SELECT SUB.ClientID, CASE (SELECT COUNT(ClientID)
FROM MyTable MT
WHERE Balance IS NULL
AND MT.ClientID = SUB.ClientID)
WHEN 0 THEN (SELECT MAX(Balance)
FROM MyTable MT
WHERE MT.ClientID = SUB.ClientID)
ELSE NULL END AS Balance
FROM (SELECT ClientID
FROM [MyTable]
GROUP BY ClientID) SUB