Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 单行中的多行_Mysql_Sql_Join_Grouping - Fatal编程技术网

Mysql 单行中的多行

Mysql 单行中的多行,mysql,sql,join,grouping,Mysql,Sql,Join,Grouping,我陷入了一个混乱的结构中,在编写查询时需要帮助,这是我当前的查询 SQL: SELECT `name` , trnid, `material` , SUM( quantity )qty , SUM( price ) price, SUM( preturn ) return FROM `transactions` a JOIN item_master b ON a.material = b.id GROUP BY material, trnid LIMIT 0 , 30 输出: SELE

我陷入了一个混乱的结构中,在编写查询时需要帮助,这是我当前的查询

SQL:

SELECT  `name` , trnid,  `material` , SUM( quantity )qty , SUM( price ) price, SUM( preturn ) return 
FROM  `transactions` a
JOIN item_master b ON a.material = b.id
GROUP BY material, trnid
LIMIT 0 , 30
输出:

SELECT  `name` , trnid,  `material` , SUM( quantity )qty , SUM( price ) price, SUM( preturn ) return 
FROM  `transactions` a
JOIN item_master b ON a.material = b.id
GROUP BY material, trnid
LIMIT 0 , 30

如果您看到上面有两条相同物料的记录(trnd 1为采购数量,trnd 2为出库数量),我希望这些记录是一条具有以下列的记录

name | material | purqty | issqty  

我认为您需要条件聚合:

SELECT  name, material,
        SUM(case when trnid = 1 then quantity else 0 end) as purchaseqty,
        SUM(case when trnid = 2 then quantity else 0 end) as issueqty
FROM transactions t JOIN
     item_master im
     ON t.material = im.id
GROUP BY name, material
LIMIT 0 , 30;

我认为您需要条件聚合:

SELECT  name, material,
        SUM(case when trnid = 1 then quantity else 0 end) as purchaseqty,
        SUM(case when trnid = 2 then quantity else 0 end) as issueqty
FROM transactions t JOIN
     item_master im
     ON t.material = im.id
GROUP BY name, material
LIMIT 0 , 30;

完美和被接受的唯一一件事是,我只需要按材料分组并删除名称,以根据我的结构得到正确的结果。谢谢:)完美且被接受的唯一一件事是我只需要按材料分组并删除名称,以根据我的结构得到正确的结果。谢谢:)