简体   繁体   中英

GROUP BY in Sub Query with SUM

I am sure I am going about this the wrong way but need some help getting an aggregate from a second table using the group by column.

My sample query below.

SELECT id, SUM(prices) "price_total", 
    (SELECT SUM(item_cost) as total_cost 
    FROM items 
    WHERE date_created=date_added) as total_items 
FROM products 
GROUP BY date_added

This is giving me an odd result where every total_items is the same amount and much larger than what is in the table. Any guidance would be appreciated.

Basically I need to get the total for that grouped date_added from the items table.

Use a JOIN rather than a correlated subquery.

SELECT p.date_added, SUM(p.prices) AS price_total, i.cost_total
FROM products AS p
JOIN (
    SELECT date_created, SUM(item_cost) AS cost_total
    FROM items
    GROUP BY date_created
) AS i ON i.date_created = p.date_added

There's no point in selecting id , since you'll just select a random product ID from each date.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM