我是 mysql 的新手
在我有问题并从某人那里得到答案之前。但我需要从查询中再次改进。
这是我在 mysql 数据库上的采样数据
表测试
通过我之前的问题下面的这个查询,我得到了我想要的结果。
select item, no_po, sum(qty) qty_total,
sum(case when child_customer='ha' then qty else 0 end) as customer_b_ha,
sum(case when child_customer='hi' then qty else 0 end) as customer_b_hi,
sum(case when child_customer='hu' then qty else 0 end) as customer_b_hu,
sum(case when child_customer='he' then qty else 0 end) as customer_b_he,
sum(case when child_customer='ho' then qty else 0 end) as customer_b_ho from test where received_date='2018-06-27' group by item, no_po order by item asc
这就是我想要的结果。
我的问题是,如何动态地仅使用带有 child_customer 变量参数键(ha、hi、hu、he、ho)的单行,直到下面的查询中的“ho”。
sum(case when child_customer='ha' then qty else 0 end) as customer_b_ha,
sum(case when child_customer='hi' then qty else 0 end) as customer_b_hi,
sum(case when child_customer='hu' then qty else 0 end) as customer_b_hu,
sum(case when child_customer='he' then qty else 0 end) as customer_b_he,
sum(case when child_customer='ho' then qty else 0 end) as customer_b_ho
注意:之前,密钥 ("ha","hi"."hu","he","ho") 我从 (SELECT distinct(child_customer) from test where received_date='2018-06-07' )
谢谢你,
最良好的问候
如果我理解你的要求,你会想要不同数量的列,具体取决于不同的 child_customer 值的数量。这被称为旋转,简短的回答是你不能在 MySQL 中。一种选择是遍历不同的 child_customer 并生成一个您可以执行的查询。您可以在存储过程或您的宿主语言中执行此操作。
但是,我建议这样的查询:
并在您的应用程序中进行旋转。