[英]Count rows that have the same value in mysql and then show item number
I have the following data and I was hoping I can group them. 我有以下数据,希望能将它们分组。
| Label | Category |
| PC Equipment | Materials |
| PC Equipment | Materials |
| PC Equipment - Install| Installation |
| Table Setup | Materials |
| Table Setup | Materials |
| Table Setup - Install | Installation |
I wanted to group the following to this output: 我想将以下内容组合到此输出中:
| Item #| Label | Category |
| | PC Equipment | Materials |
| | PC Equipment | Materials |
| 1 | PC Equipment - Install| Installation |
| | Table Setup | Materials |
| | Table Setup | Materials |
| 2 | Table Setup - Install | Installation |
Would that be possible? 那有可能吗? So far this is what I tried 到目前为止,这是我尝试过的
SELECT
@row_number := CASE WHEN Label LIKE "%Install%" THEN @row_number + 1
ELSE ""
END AS row_number,
Label
FROM table1 t,
(SELECT @rownum := 0) r
WHERE deleted = 0
The output i got was 我得到的输出是
| Item #| Label | Category |
| | PC Equipment | Materials |
| | PC Equipment | Materials |
| 1 | PC Equipment - Install| Installation |
| | Table Setup | Materials |
| | Table Setup | Materials |
| 1 | Table Setup - Install | Installation |
the second number did not increment. 第二个数字没有增加。
This is MySQL. 这是MySQL。 You just need to do the variable arithmetic correctly: 您只需要正确执行变量算术:
SELECT (CASE WHEN Label LIKE '%Install%'
THEN cast(@icnt := @icnt + 1 as char(10))
ELSE ''
END) AS row_number,
Label
FROM table1 t CROSS JOIN
(SELECT @icnt := 0) params
WHERE deleted = 0;
The reason your method doesn't work is because you are re-setting the counter variable on each row. 您的方法不起作用的原因是因为您要在每行上重新设置计数器变量。 So, it goes from 1
to ""
, and the empty string is treated as 0 -- so the next installation, it is incremented to 1. And so on. 因此,它从1
到""
,并且空字符串被视为0-因此,在下一次安装时,它将增加到1。依此类推。
Try this: 尝试这个:
SELECT IF(Label LIKE "%Install%", rn, '') AS 'Item #',
Label, Category
FROM (
SELECT @row_number := CASE
WHEN Label LIKE "%Install%" THEN @row_number + 1
ELSE @row_number
END AS rn,
Label, Category
FROM table1 AS t
(SELECT @row_number := 0) AS r
WHERE deleted = 0
ORDER BY Label) AS t
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.