0

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

采购订单表:

在此处输入图像描述

4

2 回答 2

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;
于 2016-08-30T03:35:48.227 回答
0

在 mysql 中缺少窗口函数,这将是最好的选择。

但是对于您的特定问题,这将解决问题。

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

只需使用您的表名和列名。不幸的是,如果您要添加 po4,则需要将其添加到查询中。如果你会使用例如 Postgres - 你不会有这个问题。

于 2016-08-30T04:45:15.950 回答