计算每一行的字段的不同值

时间:2015-03-26 16:18:02

标签: sql mysqli

table:item_tbl

|item_id |serial_code|item_name|
 ------------------------------
|   1    |  x35      | bullet  |
|   2    |  6ox      | cord    |
|   3    |  0hg      | cord    |
|   4    |  a73      | tv      |
|   5    |  lo5      | bullet  |

我尝试使用SELECT serial_code, item_name, COUNT(item_name) FROM item_tbl但不是我当然的预期。如何将item_name的不同值计算为:

|serial_code|item_name| count |
 -----------------------------
|  x35      | bullet  |  2    |
|  6ox      | cord    |  2    |
|  0hg      | cord    |  2    |
|  a73      | tv      |  1    |
|  lo5      | bullet  |  2    |

1 个答案:

答案 0 :(得分:2)

SELECT Serial_Code, count.Item_Name, Count
FROM 
     item_tbl i
     INNER JOIN
       (
         SELECT Item_Name, COUNT(1) Count
         FROM item_tbl
         GROUP BY item_Name
       ) count ON i.item_Name = count.Item_Name

让我们看看是否有效。