mysql - 如果值大于零,则打印列名称、计数和总和

标签 mysql

我想对值大于零的项目进行计数和求和。下面显示了以下数据和示例...我无法获取这种格式的数据。

原始数据

---------------------------------------
Id      Item_1  Item_2  Item_3  Item_4
---------------------------------------
1         0       500     0        0
2         200     0       0        0
3         350     0       0        0
4         0       0      500       0
5         0       300    0         0
6         0       0      0        400
7         0       0      200      0
---------------------------------------

我想要这种格式

--------------------
Count   ITEM    SUM
--------------------
2       Item_1  550
2       Item_2  800
2       Item_3  700
1       Item_4  400

最佳答案

您可以在此设计中使用以下查询:

select count(Item_1) as Count, 'Item_1' as ITEM, sum(Item_1) as SUM from table_name
UNION
select count(Item_2) as Count, 'Item_2' as ITEM, sum(Item_2) as SUM from table_name
UNION
select count(Item_3) as Count, 'Item_3' as ITEM, sum(Item_3) as SUM from table_name
UNION
select count(Item_4) as Count, 'Item_4' as ITEM, sum(Item_4) as SUM from table_name

但是表格设计不合适。它应该类似于下面的内容:

create table my_table
(id int, item_name varchar(50), item_sold int);

然后你可以使用case语句来比较item_name。

关于mysql - 如果值大于零,则打印列名称、计数和总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44627724/

相关文章:

mysql - mysql存储过程concat()长字符串

java - 选择“查询”,将出现在 Netbeans 和 mysql 中的组合框中

php - 在 DOM createElement 中将两个变量相乘

php - 在mysql中选择唯一的id

php - 从数组中对数据库进行排序

mysql - 创建触发器以对同一个表进行条件更新

PHP、mySQL、Google map 代码打印出 "Array",而不是数据值

mysql - 当行在该时间段之前不存在时,有 COUNT 个不同的数字

mysql - 由于 "bundle update"gem,我无法运行 "mysql2"

mysql - 查询单个分区记录很慢