gpt4 book ai didi

MYSQL 在 Group By 中使用限制

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

我有这种查询,需要在每个“区域”组中限制 3 个,但它没有按我的预期运行。 “row_number”似乎没有相应排列。一定有一些语法我错过了或者我不知道。如果有人可以帮助我转储sql Here 。 MYSQL版本5.0

我的查询:

set @type = '';
set @num = 0;

SELECT locinvaisle.Area as ar,locinvaisle.Region as rg,custlist.CustomerName as cn,custlist.Custtype ct,
SUM(data2.quantity/1000) as mtcur,
@num := if(@type = locinvaisle.Region, @num + 1, 1) as dummy_1,
@type := locinvaisle.Region as dummy_2,
@num as row_number

FROM data2

INNER JOIN custlist ON data2.customeracc = custlist.Customeraccount
INNER JOIN locinvaisle ON data2.location = locinvaisle.Location

WHERE
date1 >= DATE_FORMAT('2018-06-11', '%Y-01-01') AND date1 <= DATE_FORMAT('2018-06-11', '%Y-%m-31')
AND
data2.unit = 'KG'
AND
data2.customeracc not in (select Customeraccount from custlist WHERE Custcat = 'bcsb')
AND
locinvaisle.Area = 'peninsular'
AND
custlist.Custtype = 'others'

GROUP BY locinvaisle.Region,custlist.CustomerName
HAVING row_number < 3
ORDER BY locinvaisle.Region,mtcur desc

结果:

results

期望的结果(来自虚拟数据库):

dummy

最佳答案

在应用分组依据之前,您必须将限制作为完整子查询(“派生表”)进行。大致如下:

SELECT 
ar, rg, cn, ct, sum(quantity)
FROM (
SELECT
@row_num :=IF(@prev_value = locinvaisle.Region, @row_num + 1, 1)AS RowNumber
, locinvaisle.Area as ar
, locinvaisle.Region as rg
, custlist.CustomerName as cn
, custlist.Custtype ct
, data2.quantity
, @prev_value := locinvaisle.Region as dummy_2,
FROM data2
INNER JOIN custlist ON data2.customeracc = custlist.Customeraccount
INNER JOIN locinvaisle ON data2.location = locinvaisle.Location
CROSS JOIN (SELECT @row_num :=1, @prev_value :='') vars
WHERE date1 >= DATE_FORMAT('2018-06-11', '%Y-01-01') AND date1 <= DATE_FORMAT('2018-06-11', '%Y-%m-31')
AND data2.unit = 'KG'
AND data2.customeracc not in (select Customeraccount from custlist WHERE Custcat = 'bcsb')
AND locinvaisle.Area = 'peninsular'
AND custlist.Custtype = 'others'
ORDER BY locinvaisle.Region,mtcur desc
) d
WHERE rowNumber <= 3
GROUP BY ar, rg, cn, ct
ORDER BY ar, rg, cn, ct

注意:您需要在子查询中应用 ORDER BY 来促进行号计算,但尽管如此,仍不能保证最终输出将按照所需的顺序,除非您应用最终的按子句排序。

另请注意,在 MySQL 的 future 版本(V8 及更高版本)中,应该有一个 row_number() 函数和 over() 子句,可以用来代替上面看到的变量。

关于MYSQL 在 Group By 中使用限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52420057/

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