0

我怎样才能解决这个要求。请帮忙。

客户表 - 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  

请告诉我,还有其他选择吗?

4

5 回答 5

2

尝试这个:

Select ClientID,
       (CASE WHEN count(balance) < count(*)
             THEN NULL 
             ELSE MAX(Balance)
        END) AS MaxBalance
From CT
Group by clientID  

或者,更麻烦一点,但也许更清楚:

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  
于 2012-06-21T13:42:52.973 回答
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
于 2012-06-21T13:46:51.953 回答
1

我不确定 [Balance] 是什么数据类型,但如果它是 int,您可以执行以下操作:

Select ClientID, NULLIF(MAX(ISNULL(Balance,2147483647)),2147483647)
From CT 
GROUP BY ClientID

如果 [Balance] 不是 int,只需替换2147483647为该数据类型的最大值即可。

当然,危险是如果您确实有一个余额为 2147483647 的客户。在这种情况下,他们的最大余额将显示为空。

于 2012-06-21T14:05:28.353 回答
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
于 2012-06-21T13:57:19.057 回答
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
于 2012-06-21T13:49:30.440 回答