[英]SQL Query in finding out the max number from a table with Null value
How Can I work out this requirement. 我该如何解决这个要求。 Please help. 请帮忙。
Client Table - CT 客户表-CT
ClientID Balance
123 10
123 20
123 30
123 40
124 50
124 60
124 Null
I want to find our the max(Balance) from the CT Table. 我想从CT表中找到我们的max(Balance)。
Condition - > If there is no null value then I have to find out max(Balance) otherwise It should be Null. 条件->如果没有null值,那么我必须找出max(Balance),否则应该为Null。 See below result, that am expecting. 看到下面的结果,这是期望的。
ClientID Balance
123 40
124 Null
Am writing the query as below. 正在编写查询,如下所示。 But Is there any more dynamic way to do? 但是还有其他动态的方法吗?
Select ClientID,
CASE WHEN MIN(Balance) = NULL THEN
NULL
ELSE
MAX(Balance) END AS 'MaxBalance'
From CT
Group by clientID
Please let me know, is there any otheralternative? 请让我知道,还有其他选择吗?
Try this: 尝试这个:
Select ClientID,
(CASE WHEN count(balance) < count(*)
THEN NULL
ELSE MAX(Balance)
END) AS MaxBalance
From CT
Group by clientID
Or, a bit more cumbsersome, but perhaps clearer: 或者,更麻烦一些,但也许更清楚:
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
How about: 怎么样:
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
I'm not sure what datatype [Balance] is, but if it is an int, you can do the following: 我不确定[Balance]是什么数据类型,但是如果它是整数,则可以执行以下操作:
Select ClientID, NULLIF(MAX(ISNULL(Balance,2147483647)),2147483647)
From CT
GROUP BY ClientID
If [Balance] is not an int, just replace 2147483647
with the max value of that datatype. 如果[Balance]不是int,只需将2147483647
替换为该数据类型的最大值。
The danger, of course, would be if you really do have a client with a balance of 2147483647. In such a case their max balance would show as null. 危险当然是如果您确实有一个余额为2147483647的客户。在这种情况下,他们的最大余额将显示为空。
This will work on SQL 2005+ 这将适用于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
This works but is not very elegant: 这可行,但不是很优雅:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.