我正在尝试获取所有id_user的列表以及creditRecieved的数量和creditUsed的数量,我实际上想添加第三个选项,如果有的话,提到左边的。如果creditReceived更大,则信用额度更高。但是第一部分现在输出加倍,所以我开始在StackOverflow上进行解释,但是我无法让它工作。
SELECT
dbo.UserPurchase.CreditUsed,
dbo.UserCredit.CreditRecieved
FROM
(
SELECT SUM(dbo.UserPurchase.creditUsed) AS CreditUsed
FROM dbo.UserPurchase
)
dbo.UserPurchase LEFT JOIN
(
SELECT SUM(dbo.UserCredit.creditRecieved) AS CreditRecieved
FROM dbo.UserCredit
)
dbo.UserCredit ON dbo.UserPurchase.id_user = dbo.UserCredit.id_user
数据来自这两个表
表dbo.UserCredit
id id_user creditRecieved PurchasePrice
----------- ----------- -------------- -------------
1 1 150 750
2 1 25 100
3 2 65 15
表dbo.UserPurchase
id id_user creditUsed date
----------- ----------- ----------- -----------
1 1 175 NULL
2 2 3 NULL
3 2 2 NULL
我想得到以下结果
id_user CreditRecieved CreditUsed CreditLeftOver
----------- -------------- ----------- --------------
1 175 175 0
2 65 5 60
答案 0 :(得分:0)
如果我理解正确,你想要id_user总结的creditUsed和creditRecieved(你最后的错字?)?这将是查询:
SELECT p.id_user, SUM(p.creditUsed), SUM(u.creditRecieved)
FROM dbo.UserCredit u
LEFT JOIN dbo.UserPurchase p ON p.id_user = u.id_user
GROUP BY p.id_user
答案 1 :(得分:0)
尝试分别查询每个表:
IFooBar
SELECT users.id_user, coalesce(credit.received, 0) received,
coalesce(purchase.used, 0) Used, coalesce(credit.received, 0) - coalesce(purchase.used, 0) LeftOver, coalesce(purchase.purchaseCount, 0) purchaseCount
FROM
(
select distinct id_user from dbo.UserCredit
union
select distinct id_user from dbo.UserPurchase
) users
left outer join
(
select id_user, sum(creditRecieved) received from dbo.UserCredit group by id_user
) credit
on users.id_user = credit.id_user
left outer join
(
select id_user, sum(creditUsed) used, count(1) purchaseCount from dbo.UserPurchase group by id_user
) purchase
on users.id_user = purchase.id_user
中存在拼写错误。它应该是CreditRecieved
。答案 2 :(得分:0)
您可以使用此查询
SELECT
C.id_user,
C.CreditRecieved,
P.CreditUsed,
C.CreditRecieved - P.CreditUsed CreditLeftOver
FROM
(SELECT id_user, SUM(creditRecieved) CreditRecieved FROM UserCredit GROUP BY id_user) C
LEFT JOIN
(SELECT id_user, SUM(creditUsed) CreditUsed FROM UserPurchase GROUP BY id_user) P ON C.id_user = P.id_user