简体   繁体   English

如何在 MySQL 中实现 pivot 表 output?

[英]How can I achieve pivot table output in MySQL?

If I have a MySQL table looking something like this:如果我有一个看起来像这样的 MySQL 表:

样本数据

How to write a mysql query to get output like this:如何编写 mysql 查询以获取 output 如下所示:

userid        total_entries      products_sold
------------------------------------------------------------------
204           1011               1500
195           785                350

The idea is that we want to get total entries and sum of products sold per user.这个想法是我们想要获得每个用户的总条目和销售的产品总和。 I'm not sure if this is called a pivot table but someone suggested that?我不确定这是否称为 pivot 表,但有人建议这样做? Help me to write mysql query and if there is also date in the column and we want to get entries for today.帮我写 mysql 查询,如果列中还有日期,我们想获取今天的条目。

You could do self-joins for each attribute.您可以为每个属性进行自联接。 I'm guessing a bit at this, because your example data doesn't match the result you show.我对此有所猜测,因为您的示例数据与您显示的结果不匹配。

SELECT u.value AS userid,
  t.value AS total_entries,
  s.value AS products_sold
FROM mytable AS u
LEFT JOIN mytable AS t USING (sid)
LEFT JOIN mytable AS s USING (sid)
WHERE u.name='userid'
  AND t.name='total_entries'
  AND s.name='products_sold';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM