多个SQL选择将不同的位置选择为一个选择

时间:2016-02-27 20:08:59

标签: sql sql-server tsql select where

我有两个不同的Select语句可以产生正确的结果,但我很好奇是否可以在一个Select中完成?

SELECT UserInfo.Id, AVG(BalanceInfo.Bet) as 'Avg bet'
FROM [USERINFO] as UserInfo
JOIN [BALANCEINFO] as BalanceInfo
ON UserInfo.Id = BalanceInfo.UserId
WHERE UserInfo.RoomId = 84 AND BalanceInfo.Bet != 0
GROUP BY UserInfo.Id

SELECT UserInfo.Id, SUM(BalanceInfo.Profit) as 'Deposits'
FROM [USERINFO] as UserInfo
JOIN [BALANCEINFO] as BalanceInfo
ON UserInfo.Id = BalanceInfo.UserId
WHERE UserInfo.RoomId = 84 AND BalanceInfo.ChangeType = 8 AND BalanceInfo.Profit > 0
GROUP BY UserInfo.Id

您可能会看到区别在于Where语句。

第一个选择产生每个用户的平均投注,第二个选择产生每个用户的存款总和,这是两个不同的表。可以用一个来完成吗?

2 个答案:

答案 0 :(得分:2)

您可以在汇总函数中使用CASE语句:

SELECT UserInfo.Id, 
    AVG(CASE WHEN BalanceInfo.Bet != 0 THEN BalanceInfo.Bet ELSE NULL END) as 'Avg bet',
    SUM(CASE WHEN BalanceInfo.ChangeType = 8 AND BalanceInfo.Profit > 0 
        THEN BalanceInfo.Profit ELSE NULL END) as 'Deposits'
FROM [USERINFO] as UserInfo
JOIN [BALANCEINFO] as BalanceInfo
ON UserInfo.Id = BalanceInfo.UserId
WHERE UserInfo.RoomId = 84
GROUP BY UserInfo.Id

这里的要点是确保只为聚合函数提供匹配的值,而在其他情况下提供NULL。在聚合函数中忽略NULL个值,因此只计算所需的值

答案 1 :(得分:0)

您正在使用两个不同的表来获取和求和。以下查询可以帮助您实现这一目标。

SELECT UserInfo.Id, AVG(BalanceInfo.Bet) as 'Avg bet',SUM(BalanceInfo.Profit) as 'Deposits' FROM [USERINFO] as UserInfo JOIN [BALANCEINFO] as BalanceInfo ON UserInfo.Id=BalanceInfo.UserId WHERE UserInfo.RoomId = 84 AND BalanceInfo.Bet != 0 AND BalanceInfo.ChangeType = 8 AND BalanceInfo.Profit > 0 GROUP BY UserInfo.Id