gpt4 book ai didi

MySQL 嵌套 SELECT

转载 作者:行者123 更新时间:2023-11-29 05:36:25 25 4
gpt4 key购买 nike

我对这个查询感到困惑。我有一张看起来像这样的表格(简化版):

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 子句复制粘贴到子查询中,但没有成功。

最佳答案

使用 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`))

关于MySQL 嵌套 SELECT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10179821/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com