如何通过外部联接查询执行组功能?

时间:2019-04-14 12:40:08

标签: sql sql-server tsql

我有以下类别:

category_id                             name
-----                                   -----
50D34E5A-A935-490A-9492-153DE50A94A2    Luxuries
013E3D0F-E755-495B-8D1E-4A3D1340ACF8    Household
88C477EE-CF99-49B4-9E92-4C41B09A5715    Petrol
40099E3A-18F1-4710-A803-7107648518CC    Other
E3B81693-07B5-4D69-A3EC-796CA4290B45    Rent
F0728052-0733-454B-B8EE-96AB6D6E40BE    Insurance
6E06581A-1643-4DEC-90B7-9D57F770F313    Groceries
CFD1ED67-7059-4A33-8DD6-F2FFAB213970    Monthly Bill

以及以下交易(在category_id上缩短并加入):

category_id    amount
------         -----
Luxuries       14
Household      14
Petrol         14
Other          14
Rent           14
Insurance      14

没有Groceries个交易。我想将这些金额相加并显示其数量,但在结果中包括Groceries,但显示为零。我已经尝试过了:

SELECT SUM(ut.amount), COUNT(ut.amount), c.name
FROM User_Transaction ut
FULL OUTER JOIN Category c ON (ut.category_id = c.category_id)
GROUP BY c.name



total   count   name
---     ---     ---
84      6       Household
84      6       Insurance
84      6       Luxuries
98      7       Monthly Bill
56      4       Other
182     13      Petrol
112     8       Rent

但是Groceries未包括在内。如何在结果集中包含Groceries,但仅显示为0

1 个答案:

答案 0 :(得分:1)

使用以LEFT JOIN开头的category(您要保留的值):

SELECT c.name, COALESCE(SUM(ut.amount), 0) as amount,
       COUNT(ut.category_id) as num_transactions, 
FROM Category c LEFT JOIN
     User_Transaction ut
     ON ut.category_id = c.category_id
GROUP BY c.category_id, c.name;

也就是说,我认为您的查询应该执行您想要的操作,尽管在这种情况下使用full join会产生误导。