在GROUP BY()之后过滤数据,反之亦然?

时间:2014-02-19 14:51:57

标签: mysql sql database

以下是MySQL中的表格

Table:ShopInfo

ShopCode     ShopName
--------     -------
X            Xylophon
Y            Yellow
Z            Zoota
K            Kite

Table: Income

Shop     Date           Earnings
-----    ----------     --------
X        2014-10-17     4000
Y        NULL           NULL
Y        2014-11-09     5000
Y        2014-11-18     3000
Y        2014-12-05     2000
Z        2014-12-25     6000
K        NULL           NULL

我想找到11月份每个商店的总收入,Null收入将被替换为零。结果表将是

ShopName    NovEarn
--------    -------
Yellow      8000
Kite        0 

这就是我在做什么:

SELECT ShopInfo.ShopName, IFNULL( SUM(Income.Earnings), 0 ) AS NovEarn
FROM Income
JOIN ShopInfo ON Income.Shop=ShopName.ShopCode
GROUP BY Income.Shop
HAVING (MONTH(Income.Date)=11 AND YEAR(Income.Date)=2014) OR Date IS NULL
ORDER BY NovEarn DESC

它给了我

ShopName    NovEarn
--------    -------
Yellow      10000
Kite        0

即所有月份的收入总和。我做错了什么?

4 个答案:

答案 0 :(得分:1)

按照显示代码分组之前,必须按月过滤收入。对该部分使用where语句。但是你会遇到让商店没有收入的问题。所以你应该先从ShopInfo中选择,然后再加入收入,这样如果没有可接受的收入,商店仍会显示。

SELECT ShopInfo.ShopName, IFNULL( SUM(Income.Earnings), 0 ) AS NovEarn
FROM ShopInfo
LEFT JOIN Income ON ShopName.ShopCode = Income.Shop
WHERE (MONTH(Income.Date)=11 AND YEAR(Income.Date)=2014)
GROUP BY ShopInfo.ShopCode
ORDER BY NovEarn DESC

答案 1 :(得分:1)

您在列HAVING上的Income.Date条件中没有分组。

您应该将日期条件设置为WHERE子句。

类似的东西:

SELECT ShopInfo.ShopName, IFNULL( SUM(Income.Earnings), 0 ) AS NovEarn
FROM Income
JOIN ShopInfo ON Income.Shop=ShopName.ShopCode
WHERE (MONTH(Income.Date)=11 AND YEAR(Income.Date)=2014)
GROUP BY Income.Shop
ORDER BY NovEarn DESC

答案 2 :(得分:1)

尝试将having子句放在where子句下:

SELECT ShopInfo.ShopName, IFNULL( SUM(Income.Earnings), 0 ) AS NovEarn
FROM Income
JOIN ShopInfo ON Income.Shop=ShopName.ShopCode
WHERE (MONTH(Income.Date)=11 AND YEAR(Income.Date)=2014) OR Date IS NULL
GROUP BY Income.Shop
ORDER BY NovEarn DESC

答案 3 :(得分:0)

SELECT ShopInfo.ShopName, SUM(COALESCE(Income.Earnings,0)) AS NovEarn
FROM Income
JOIN ShopInfo ON Income.Shop=ShopName.ShopCode
WHERE (MONTH(Income.Date)=11 AND YEAR(Income.Date)=2014) OR Date IS NULL
GROUP BY Income.Shop
ORDER BY NovEarn DESC