简体   繁体   中英

How to query group in mysql

i have two table

tblstock

id name stock
1 aa 20
2 ab 25
3 ac 30

tblinputs

id name lot qty
1 aa 1.01 5
2 aa 1.02 5
3 aa 2.03 10
4 ab 3.04 15
5 ab 2.03 10
6 ac 1.01 10
7 ac 1.04 10
8 ac 2.01 10

how to implement query join and group by on below result

id name lot1 lot 2 lot 3 lot 4 stock
1 aa 1.01 1.02 2.03 0 20
2 ab 3.04 2.03 0 0 25
3 ac 1.01 2.01 1.04 0 30

i has try, but not succes

SELECT name, lot FROM tblinputs INNER JOIN tblitems ON tblitems.id=tblinputs.name GROUP BY lot

I you can live without the lot1-lot4 headers a group_concat is the simplest way to go

SELECT ts.id,ts.name,group_concat(ti.lot order by ti.id) lots,max(ts.stock) qty
from tblstock ts
join tblinputs ti on ti.name = ts.name
group by ts.id,ts.name;

if you do need the headers then assign a row_number and conditionally aggregate

with cte as(
SELECT ts.id,ts.name,row_number() over(partition  by ts.id order by ti.id) rn,
        ti.lot
from tblstock ts
join tblinputs ti on ti.name = ts.name
),
cte1 as
(select cte.id,cte.name,
        max(case when rn = 1 then cte.lot else 0 end) lot1,
        max(case when rn = 2 then cte.lot else 0 end) lot2,
        max(case when rn = 3 then cte.lot else 0 end) lot3,
        max(case when rn = 4 then cte.lot else 0 end) lot4
from cte
group by cte.id,cte.name
)
select cte1.* , ts.stock
from cte1
join tblstock ts on ts.id = cte1.id;

if there can be an unknown, possibly infinite number of lots per id then you need to go dynamic sql

https://dbfiddle.uk/mceDn-Zk

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