我有一个表,其中包含客户的默认契约(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/