表:购物
shop_id shop_building shop_person shop_time
1 1 Brian 40
2 2 Brian 31
3 1 Tom 20
4 3 Brian 30
表:建筑物
building_id building_city
1 London
2 Newcastle
3 London
4 London
表:香蕉
banana_id banana_building banana_amount banana_person
1 2 1 Brian
2 3 1 Brian
2 1 1 Tom
我现在希望它向我展示每个人在伦敦购买的香蕉数量。
我使用了这段代码:
SELECT tt.*, tu.*, tz.*,
SUM(shop_time) AS shoptime,
Ifnull(banana_amount, 0) AS bananas
INNER JOIN buildings tu ON tt.shop_building=tu.building_id
FROM shopping tt
LEFT OUTER JOIN (SELECT banana_person, banana_building,
SUM(banana_amount) AS banana_amount
FROM bananas
GROUP BY banana_person) tz
ON tt.shop_person = tz.banana_person AND tt.shop_building = tz.banana_building
WHERE tu.building_city = 'London'
GROUP BY shop_person;
但它不起作用。这就好像我告诉它为时已晚,它应该只在伦敦看,因为它忽略了这一点。
答案 0 :(得分:1)
尝试这种方式:
SELECT
s.shop_person, sum(b.banana_amount) as Amt, , sum(shop_time) as TimeAmt
FROM bananas b
INNER JOIN buildings bu ON b.banana_building = bu.building_id
INNER JOIN shopping s ON bu.building_id = s.shop_building
WHERE
bu.building_city = N'London'
GROUP BY s.shop_person
这个查询不同,但它可以做你想要的 - “每个人在伦敦购买的香蕉数量”
答案 1 :(得分:0)
在不知道您使用的数据库的情况下,这是mssql的工作版本。 我实际上重建了表格以确保它是正确的。
对于其他数据库系统,您可能必须在SELECT语句中使用除ISNULL
之外的其他函数。
SELECT tt.shop_person,
tt.shop_building,
SUM(tt.shop_time) AS shoptime,
ISNULL(SUM(tz.banana_amount), 0) AS bananas
FROM dbo.shopping tt
INNER JOIN dbo.buildings tu ON tt.shop_building = tu.building_id
LEFT OUTER JOIN
(SELECT banana_person, banana_building, SUM(banana_amount) AS banana_amount
FROM bananas
GROUP BY banana_person, banana_building) tz
ON tt.shop_person = tz.banana_person AND tt.shop_building = tz.banana_building
WHERE (tu.building_city = 'London')
GROUP BY tt.shop_person, tt.shop_building
我必须在tz.banana_amount
附近添加一个聚合函数 - 其中一个(SUM,MIN,MAX)无关紧要。
结果:
shop_person shop_building shoptime bananas
Brian 1 40 0
Tom 1 20 1
Brian 3 30 1
我在bananas
等中玩了不同数量的游戏,但它运行正常。