MySQL查询整合表

时间:2016-08-30 03:21:22

标签: mysql sql consolidation

你能帮我创建一个将第一个表(左)转换为第二个表(右)的查询。我需要将产品代码合并到采购订单中。

PO表:

enter image description here

2 个答案:

答案 0 :(得分:0)

这是查询

SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
  'count(case when PONumber = ''',
  PONumber,
  ''' then 1 end) AS ',
  replace(PONumber, ' ', '')
 )
) INTO @sql
 from PO;

SET @sql = CONCAT('SELECT pt.ProductCode, ', @sql, ' from PO pt
group by ProductCode');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

答案 1 :(得分:0)

In mysql there is lack o window functions which will be the best thing here.

But for your particular problem this will solve the issue.

SELECT 
    product_code,
    (SELECT count from your_table t2 
        Join t1 on t2.product_code = t1.product_code and t2.po_number = 'PO1') as PO1,
     (SELECT count from your_table t3
        Join t1 on t3.product_code = t1.product_code and t3.po_number = 'PO2') as PO2,
     (SELECT count from your_table t4
        Join t1 on t4.product_code = t1.product_code and t5.po_number = 'PO3') as PO3
From your_table t1

Just use your table name and column names. Unfortunately if you will add po4 you need to add it to the query. If you would use for example Postgres - you would not have this problem.

相关问题