在表中获取相同的行

时间:2012-08-20 06:04:40

标签: php mysql

好的,我有这种结构的表格:

order_id product_id price

18645 289 5.90

18644 219 1.80

18644 109 2.30

18643 289 4.50

18642 180 9.80

18642 190 3.40

我如何计算product_id's范围内的同一order_id's以及每组product_ids的相应总价?

3 个答案:

答案 0 :(得分:2)

要明智地了解产品COUNTSUM,您需要使用aggregate functions GROUP BY product_id:

SELECT product_id,
       COUNT(1) AS product_count,
       SUM(price) AS total_price
FROM table_name
WHERE order_id BETWEEN 18642  AND 18645
GROUP BY product_id
ORDER BY product_count ASC, total_price ASC 

答案 1 :(得分:2)

尝试

SELECT PRODUCT_ID,
       COUNT(product_id) totalCount,
       SUM(price) totalPrice
FROM tableName
WHERE Order_ID BETWEEN 00001  AND 99999
GROUP BY PRODUCT_ID

答案 2 :(得分:0)

试试这个:

您只需按product_id分组

select product_id,
       count(*) as count ,
       sum(price) as price
from   <table>
where  order_id beteen <val1> and <val2>
group by product_id