1

表:购物

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; 

但它不起作用。就好像我说得太晚了,它应该只看伦敦,因为它忽略了这一点。

4

2 回答 2

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

这个查询是不同的,但它可以满足您的需求 - “每个人在伦敦购买的香蕉数量”

于 2011-01-13T12:42:44.557 回答
0

在不知道您使用的是什么数据库的情况下,这里是 mssql 的工作版本。我实际上重建了表格以确保它是正确的。

对于其他数据库系统,您可能必须使用ISNULLSELECT 语句之外的其他函数。

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等,它工作正常。

于 2011-01-13T12:45:59.923 回答