简体   繁体   中英

MySQL group and sum with joined tables

I've got pretty tricky problem with MySQL.

I have two tables with one to many relation (below colums that are relevant)

Table A (campaigns):

id | channel_type | date

Table B (budgets):

id | campaign_id | budget

I need single query to fetch following result:

  • Campaign count by channel_type
  • Sum of all budgets that are related to found campaigns.

I need to filter results by columns in campaigns table (eg WHERE campaigns.date > '2014-05-01')

I have tried following approach:

SELECT channel_type, COUNT(*) cnt, 
   (SELECT SUM(budget) FROM budgets WHERE budgets.campaign_id = campaigns.id)) 
       as budget 
FROM campaigns 
WHERE campaigns.date >= 'some-value' 
    AND [more conditions] 
GROUP BY campaigns.channel_type

But this of course fails miserably because of GROUP i am getting only first campaigns.id result for channel_type.

Any tips (and solution) would be really appreciated!

TIA

  1. Get the total budget from budgets table using GROUP BY campain_id. It will be subquery. Name it. For example, A.
  2. Now get the total id counts from campains using GROUP BY channel_type and WHERE date>='some-value'.
  3. Use step 2 and 1(the subquery will act as table) in the final query and you will get the results. You can post schema and then I can check.

I think this should work :

SELECT channel_type, COUNT(*) cnt, 
   (SELECT SUM(t2.budget) FROM budgets t2 WHERE t2.campaign_id IN (
     SELECT t3.id FROM campaigns t3 WHERE t3.channel_type = t1.channel_type)) 
   AS budget 
FROM campaigns t1
WHERE t1.date >= 'some-value' 
    AND [more conditions] 
GROUP BY t1.channel_type

see this fiddle

I've found working solution. Here's working query:

SELECT SUM(budget) as budget, COUNT(*) as count FROM
    (SELECT * FROM campaigns WHERE [conditions]) AS found_campaigns
    LEFT JOIN budgets ON budgets.campaign_id = found_campaigns.id
    GROUP BY channel_type

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