[英]Count rows that have the same value in mysql and then show item number
我有以下數據,希望能將它們分組。
| 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 |
第二個數字沒有增加。
這是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。依此類推。
嘗試這個:
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.