gpt4 book ai didi

php - 如何使用group by获取MySql中的特定部分?

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

我在 SQL 查询方面遇到问题,我会尝试解释我想要做什么。这是我的查询,它返回一些结果行。

SELECT 
sck.sckid,
sck.prid,
sck.paid,
sck.sckcen,
sum(scd.scdkiek) as count_of_goods,
min(scn.scndat) as `date`
FROM sck
INNER JOIN scd ON scd.sckid = sck.sckid
INNER JOIN scn ON scn.scnid = scd.scnid
INNER JOIN sandeliai ON sandeliai.paid = sck.paid
WHERE sck.prid = 1376 GROUP BY sckid

此查询返回结果“表 1”:

表 1:

sckid    |    prid    |    sckcen    |    count_of_goods    |      date     |
123 | 1376 | 10009 | 0 | 2012-12-31 |
124 | 1376 | 10007 | 15 | 2013-01-25 |
125 | 1376 | 10005 | 0 | 2013-02-13 |
126 | 1376 | 10000 | 18 | 2013-03-15 |

但我只需要一行,其中所有数据均按 prid 分组,我编写了以下查询:

SELECT 
sck.sckid,
sck.prid,
sck.paid,
sck.sckcen,
sum(scd.scdkiek) as count_of_goods,
min(scn.scndat) as `date`
FROM sck
INNER JOIN scd ON scd.sckid = sck.sckid
INNER JOIN scn ON scn.scnid = scd.scnid
INNER JOIN sandeliai ON sandeliai.paid = sck.paid
WHERE sck.prid = 1376 GROUP BY prid

然后我在表中得到一行包含此数据的数据:

表 2:

sckid    |    prid    |    sckcen    |    count_of_goods    |      date     |
123 | 1376 | 10009 | 23 | 2012-12-31 |

这似乎都是正确的,但在 date 字段中,我需要从表一返回最早的日期,其中 count_of_goods > 0,所以对我来说需要这个结果:

表3:

sckid    |    prid    |    sckcen    |    count_of_goods    |      date     |
123 | 1376 | 10009 | 23 | 2013-01-25 |

那么我有什么想法可以得到如表 3 所示的结果吗?

最佳答案

我认为我最初得到的答案可能过于复杂。假设 scd.scdkiek 是数字而不是 id,那么您可以通过简单地更改 INNER JOIN 标准来获得您想要的内容,即

SELECT 
sck.sckid,
sck.prid,
sck.paid,
sck.sckcen,
scn.scndat,
SUM(scd.scdkiek) AS count_of_goods
FROM sck
INNER JOIN scd
ON scd.sckid = sck.sckid
AND scd.scdkiek > 0
INNER JOIN sandeliai
ON sandeliai.paid = sck.paid
INNER JOIN scn
ON scn.scnid = scd.scnid
WHERE sck.prid = 1376
GROUP BY
sck.prid

如果做不到这一点,我会考虑使用子查询。子查询将计算每行的 count_of_goods。然后,外部查询将使用它来决定是否将该行的日期设置为 NULL。 MIN(...somedate...,NULL) 将返回日期。这反过来意味着您应该获得该行上的 count_of_goods 不为 NULL 的最小日期。

当您查找 count_of_goods > 0 的日期时,子查询按日期分组。

当然这只是一种选择,可能还有其他更有效的方法,但我相信这会达到您的目的

SELECT
sck.sckid,
sck.prid,
sck.paid,
sck.sckcen,
SUM(d.count_of_goods) AS count_of_goods,
MIN(IF(d.count_of_goods>0,d.scndat,NULL)) AS `date`
FROM (
-- Get the data and group it by date
SELECT
sck.sckid,
sck.prid,
sck.paid,
sck.sckcen,
scn.scndat,
SUM(scd.scdkiek) AS count_of_goods
FROM sck
INNER JOIN scd ON scd.sckid = sck.sckid
INNER JOIN sandeliai ON sandeliai.paid = sck.paid
INNER JOIN scn ON scn.scnid = scd.scnid
WHERE sck.prid = 1376
GROUP BY
sck.prid, -- may not really be needed
scn.scndat
) AS d
GROUP BY d.prid

关于php - 如何使用group by获取MySql中的特定部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16185095/

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