mysql在当前行增加值并为每组重置

标签 mysql

我有一个表,其中包含客户的默认契约(Contract)编号,我尝试添加每个契约(Contract)的部分内容。在本例中,我使用 Number 列作为组合 contract id 与每个客户端的连续行数。

这是查询

select '0' as Id, CONCAT(ea.Id, '-', count(loc.Id)) as Number, loc.* 
from EnergyAgreement ea 
left join (
    select 1545 as Id, 301005 as custId UNION ALL
    select 2454 as Id, 301005 as custId UNION ALL
    select 3654 as Id, 301005 as custId UNION ALL
    select 1546 as Id, 301008 as custId UNION ALL
    select 2454 as Id, 301008 as custId             
) as loc ON loc.custId = ea.CustomerId 
where ea.CustomerId IN (301005, 301008)
group by loc.Id, loc.custId  
order by Number ASC`

这是错误的结果(参见Number列)

"Id" "Number" "Id"   "custId"
"0"  "77-1"   "1545" "301005"
"0"  "77-1"   "2454" "301005"
"0"  "77-1"   "3654" "301005"
"0"  "81-1"   "2454" "301008"
"0"  "81-1"   "1546" "301008"

如何构建查询以连续递增 Number 列,直到下一个 customer ID 出现,以便我可以获得如下正确的设置结果?:

"Id" "Number" "Id"   "custId"
"0"  "77-1"   "1545" "301005"
"0"  "77-2"   "2454" "301005"
"0"  "77-3"   "3654" "301005"
"0"  "81-1"   "2454" "301008"
"0"  "81-2"   "1546" "301008"

最佳答案

只需在 loc 子查询中添加所需的值即可:

select '0' as Id, CONCAT(ea.Id, '-', loc.n) as Number, loc.id, loc.custId
from EnergyAgreement ea left join
     (select 1545 as Id, 301005 as custId, 1 as n UNION ALL
      select 2454 as Id, 301005 as custId, 2 UNION ALL
      select 3654 as Id, 301005 as custId, 3 UNION ALL
      select 1546 as Id, 301008 as custId, 1 UNION ALL
      select 2454 as Id, 301008 as custId, 2          
     ) loc
     on loc.custId = ea.CustomerId 
where ea.CustomerId IN (301005, 301008)
group by loc.Id, loc.custId, loc.n 
order by Number ASC`

关于mysql在当前行增加值并为每组重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29513098/

相关文章:

php - 无法从具有数组的查询填充表

mysql - SQL查询将2个表中的数据更新到另一个表中

Mysql查询匹配两列

mysql - 双连接(一个来自同一个表,一个来自不同表)

php - 每当我使用 PHP 将数据添加到 MySQL 时,如何获取 TIMESTAMP?

mysql - 如何将唯一 ID 添加到 mysql 表?

mysql - 在 MySql 中计算组内的不同重复项

MySQL 检查给定的时间段是否在提供的时间段之间

php - WHOIS API JSON 数组内容

mysql - Hibernate 位置参数不存在 : 1 in query