我有以下数据,我希望我可以将它们分组。
| Label | Category |
| PC Equipment | Materials |
| PC Equipment | Materials |
| PC Equipment - Install| Installation |
| Table Setup | Materials |
| Table Setup | Materials |
| Table Setup - Install | Installation |
我想将以下内容分组到此输出中:
| 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 |
这可能吗? 到目前为止,这是我试过的
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
我得到的输出是
| 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 |
第二个数字没有增加。
答案 0 :(得分:2)
这是MySQL。你只需要正确地进行变量算术:
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;
您的方法不起作用的原因是您在每行重新设置计数器变量。因此,它从1
变为""
,空字符串被视为0 - 因此下一次安装时,它会增加到1.依此类推。
答案 1 :(得分:0)
试试这个:
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