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. 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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.