我有像
这样的数据|id|id_barang|in|out|stock|
|1|1|2|0|2|
|2|1|2|0|4|
|3|1|0|1|3|
|4|2|2|0|2|
|5|2|1|0|3|
|6|2|0|1|2|
我希望结果是id_barang
组|Id_barang|sum(in)|sum(out)|first(stock)|
|1|4|1|2|
|2|3|1|2|
答案 0 :(得分:0)
您可以将 MIN 功能用于第一个库存。它的工作方式与 SUM 或 COUNT 类似。
答案 1 :(得分:0)
您可以尝试以下方式:
SELECT Id_barang, SUM(in), SUM(out), FIRST(stock)
FROM data
GROUP BY Id_barang
答案 2 :(得分:0)
不幸的是Mysql
不支持Window functions
。试试这个
SELECT b.id_barang,
sum_in,
sum_out,
a.stock
FROM yourtable A
INNER JOIN (SELECT id_barang,
Sum(in) sum_in,
Sum(OUT) sum_out,
Min(id) AS min_id
FROM yourtable
GROUP BY id_barang) B
ON a.id_barang = b.id_barang
AND a.id = b.min_id
答案 3 :(得分:0)
此查询通过Id_barang获取表组的所有记录。它给出了第一份库存记录
SELECT t1.Id_barang, sum(t1.in), sum(t1.out), (select min(t2.stock)
from table_name t2 where t2.Id_barang = t1.Id_barang)
FROM table_name t1
GROUP BY Id_barang
答案 4 :(得分:0)
你可以这样查询:
SELECT id_barang,SUM(in) as total_in,SUM(out) as total_out,stock
FROM stock
GROUP BY id_barang
如果您发现任何错误,那么您必须更改您的列名称,我认为'在'和' out'无效。你改变了' in'进入' in_change'和' out'进入' out_change'。尝试使用此列,它可以根据需要使用。我确实试过......
SELECT id_barang,SUM(in_change) as total_in,SUM(out_change) as total_out,stock
FROM stock
GROUP BY id_barang