简体   繁体   中英

Auto-increment with Group BY

I have two tables as follows:

Contract

合同|

Contractuser

合同用户

My job was to fetch latest invoice date for each contract number from Contractuser table and display results. The resultant table was as follows:

Result Table

结果表

Now I wanted to get a auto-increment column to display as the first column in my result set.

I used the following query for it:

SELECT @i:=@i+1 AS Sno,a.ContractNo,a.SoftwareName,a.CompanyName,b.InvoiceNo,b.InvoiceDate,
b.InvAmount,b.InvoicePF,max(b.InvoicePT) AS InvoicePeriodTo,b.InvoiceRD,b.ISD
     FROM contract as a,contractuser as b,(SELECT @i:=0) AS i
     WHERE a.ContractNo=b.ContractNo
     GROUP BY b.ContractNo
     ORDER BY a.SoftwareName ASC;

But it seems that the auto-increment is getting performed before the group by procedure because of which serial numbers are getting displayed in a non contiguous manner.

GROUP BY and variables don't necessarily work as expected. Just use a subquery:

SELECT (@i := @i + 1) AS Sno, c.*
FROM (SELECT c.ContractNo, c.SoftwareName, c.CompanyName, cu.InvoiceNo, cu.InvoiceDate,
             cu.InvAmount, cu.InvoicePF, max(cu.InvoicePT) AS InvoicePeriodTo, cu.InvoiceRD, cu.ISD
      FROM contract c JOIN
           contractuser as b
           ON c.ContractNo = cu.ContractNo
      GROUP BY cu.ContractNo
      ORDER BY c.SoftwareName ASC
     ) c CROSS JOIN
     (SELECT @i := 0) params;

Notes:

  • I also fixed the JOIN syntax. Never use commas in the FROM clause.
  • I also added reasonable table aliases -- abbreviations for the tables. a and b don't mean anything, so they make the query harder to follow.
  • I left the GROUP BY with only one key. It should really have all the unaggregated keys but this is allowed under some circumstances.

SELECT @row_no:= IF(@prev_val = lpsm.lit_no, @row_no + 1, 1) AS row_num,@prev_val:= get_pad_value(lpsm.lit_no,26) LAWSUIT_NO,lpsm.cust_rm_no
FROM lit_person_sue_map lpsm,(SELECT @row_no:= 0) x,(SELECT @prev_val:= '') y ORDER BY lpsm.lit_no ASC;

This will return sequence number group by lit_no;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM