【问题标题】:MySQL query to consolidate tableMySQL查询合并表
【发布时间】:2016-08-30 03:21:21
【问题描述】:

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

采购订单:

【问题讨论】:

标签: mysql sql consolidation


【解决方案1】:

在 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 - 您就不会遇到这个问题。

【讨论】:

    【解决方案2】:

    这里是查询

    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;
    

    【讨论】:

    • 感谢您的回复。但是这个查询没有得到我需要的结果。
    • 我确实希望对它进行一些更改。如果您可以提供示例数据将节省时间!
    猜你喜欢
    • 2015-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    相关资源
    最近更新 更多