使用group by在mysql中选择count,然后在每行中重复计数

时间:2016-08-03 10:00:24

标签: java mysql sql database select

我的桌子名为'bill',如下所示

Bill         item          totalprice

BILL_1       Fossil Watch  9000
BILL_1       Fastrack      -
BILL_1       Fastrack      -
BILL_2       Woodlands     7000
BILL_2       Woodlands     -
BILL_3       Denim Shirt   9000
BILL_3       Levis Jean    -

现在我需要结果如下面的结构

Bill         item          totalprice  bill_count

BILL_1       Fossil Watch  9000         3
BILL_1       Fastrack      -            3
BILL_1       Fastrack      -            3
BILL_2       Woodlands     7000         2
BILL_2       Woodlands     -            2
BILL_3       Denim Shirt   9000         2
BILL_3       Levis Jean    -            2

我尝试使用以下查询,

SELECT bill,item,totalPrice,COUNT(bill) FROM bills GROUP BY bill;

但我没有按预期得到结果。

2 个答案:

答案 0 :(得分:4)

SELECT b.bill, b.item, b.totalPrice, tmp.cnt
FROM bills b
JOIN
(
   select bill, COUNT(bill) as cnt
   from bills
   group by bill
) tmp on tmp.bill = b.bill

答案 1 :(得分:3)

select bill,item,totalPrice,(SELECT 
COUNT(b1.bill)
FROM
bills AS b1 where b1.bill= b.bill
GROUP BY bill) AS bill_count from bills AS b