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

时间:2015-04-08 11:16:36

标签: mysql

我有一张表格,其中包含客户的默认合约编号,我尝试添加每份合约的部分内容。在这种情况下,我将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"

2 个答案:

答案 0 :(得分:1)

只需在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`

答案 1 :(得分:0)

我认为你需要像this solution at Method 2这样的解决方案:

select '0' as Id, CONCAT(@Id:=ea.Id, '-', @row_number:=CASE WHEN @Id=loc.Id THEN @row_number+1 ELSE 1 END) 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, (SELECT @row_number:=0,@Id:='') AS t
where ea.CustomerId IN (301005, 301008)
group by loc.Id, loc.custId  
order by Number ASC`

我现在无法测试它,但我认为它应该可行;)。