MySQL嵌套SELECT

时间:2012-04-16 18:47:28

标签: mysql sql aggregate-functions pivot-table

我对这个问题感到满意。我有一张看起来像这样的表(简化):

Date         Weight kg
-------------------
2012-04-16     12.4
2012-04-17      9.6
2012-04-16      5.4
2012-04-18      2.8
2012-04-16      4.5
...             ...

我希望查询返回此结果:

Week.no.  <3kg  3-7kg   >7kg
----------------------------
16         2.8    9.9   22.0
...        ...    ...   ....

这是我到目前为止所做的:

SELECT *, CONCAT(WEEK(`Date`)) AS Week, SUM(`Weight`) AS TotalWeight,
   (SELECT SUM(`Weight`) FROM tbl_fangster WHERE `Weight` < 3 AND
   `Date` >= '2012-04-01 00:00:00' AND `Date` <= '2012-04-30 00:00:00'
   AND `Species` = 'Salmon' ) AS SumSmall
FROM tbl_fangster
WHERE `Date` >= '2012-04-01 00:00:00'
AND `Date` <= '2012-04-30 00:00:00'
AND `Species` = 'Salmon'
GROUP BY CONCAT(WEEK(`Date`))

但SumSmall在每一行返回相同的数字,即每周总SumSmall而不是SumSmall。我试图将我的GROUP子句复制到子查询中,但它没有用。

1 个答案:

答案 0 :(得分:3)

使用CASE语句来处理各种条件。

SELECT *, CONCAT(WEEK(`Date`)) AS Week, SUM(`Weight`) AS TotalWeight,
       SUM(CASE WHEN Weight < 3 THEN Weight ELSE 0 END) AS SumSmall,
       SUM(CASE WHEN Weight >= 3 AND Weight <= 7 THEN Weight ELSE 0 END) AS SumMedium,
       SUM(CASE WHEN Weight > 7 THEN Weight ELSE 0 END) AS SumLarge
FROM tbl_fangster
WHERE `Date` >= '2012-04-01 00:00:00'
AND `Date` <= '2012-04-30 00:00:00'
AND `Species` = 'Salmon'
GROUP BY CONCAT(WEEK(`Date`))