在mysql中的SUM和Group by Logical问题

时间:2014-05-13 13:11:35

标签: mysql join count group-by

我有三张桌子

City(Id,CityName)
Malls(Id,MallName,CityId)
Stores(Id,StoreName,MallId)

我想要的是:

1 =我想在每个城市找到所有商店的总和

2 =如果CityId IN(1,2,3,5)

,查找每个城市的商店总和

3 =如果CityId IN(4,6,7,8)

,则查找每个城市的商店总数

我尝试了这个但是不能再进一步了

select count(id) FROM Stores AS s ,Malls AS m,City AS c where s.mallid=m.id and m.cityid=c.id GROUP BY c.id

2 个答案:

答案 0 :(得分:1)

每个城市的商店数量:

SELECT c.CityName, COUNT(c.id) AS StoresInCity
FROM Stores s
INNER JOIN Malls m ON s.mallid = m.id
INNER JOIN City c ON m.cityid = c.id
GROUP BY c.CityName

每个城市的商店数量为CityId IN(1, 2, 3, 5)

SELECT c.CityName, COUNT(c.id) AS StoresInCity
FROM Stores s
INNER JOIN Malls m ON s.mallid = m.id
INNER JOIN City c ON m.cityid = c.id
WHERE m.CityId IN (1, 2, 3, 5)
GROUP BY c.CityName

每个城市的商店数量为CityId IN(4, 6, 7, 8)

SELECT c.CityName, COUNT(c.id) AS StoresInCity
FROM Stores s
INNER JOIN Malls m ON s.mallid = m.id
INNER JOIN City c ON m.cityid = c.id
WHERE m.CityId IN (4, 6, 7, 8)
GROUP BY c.CityName

答案 1 :(得分:0)

这是一个查询,它为您提供了所有3个答案:

SELECT cityId,
       storesPerCity,
       SUM (CASE WHEN cityId IN (1,2,3,5) THEN storesPerCity ELSE 0 END) NumStores1_2_3_5,
       SUM (CASE WHEN cityId IN (4,6,7,8) THEN storesPerCity ELSE 0 END) Other
FROM (
       SELECT c.Id cityId,
              COUNT(*)  storesPerCity         
       FROM Stores s INNER JOIN 
            Malls m ON s.Mallid = m.Id INNER JOIN
            City c ON m.CityId = c.Id
       GROUP BY c.Id) x
GROUP BY cityId, storesPerCity