简体   繁体   中英

I need a query that will get the sum(column) with 4 different where conditions which includes group by condition

Here's my query:

SELECT
    date,
    (SELECT sum(sessions) as org FROM datatwo WHERE medium='Organic Search' GROUP by date),
    (SELECT sum(sessions) as soc FROM datatwo WHERE medium='Social' GROUP BY date),
    (SELECT sum(sessions) as dir FROM datatwo WHERE medium='Direct' group by date),
    (SELECT sum(sessions) as ref FROM datatwo WHERE medium='Referral')
FROM datatwo
GROUP BY date

I am trying to combine 4 queries in a single query but I am getting this error, I am using mysql DB.

1242 - Subquery returns more than 1 row

When you use the result of a query as a column, it must return exactly one row and one column. Expressions like this:

(SELECT sum(sessions) as org FROM datatwo WHERE medium='Organic Search' GROUP by date)

will return one row for every distinct date value.

I suspect you want this:

SELECT
    date,
    sum(case when medium='Organic Search' then sessions end) as org,
    sum(case when medium='Social' then sessions end) as soc,
    sum(case when medium='Direct' then sessions end) as dir,
    sum(case when medium='Referral' then sessions end) as ref
FROM datatwo
GROUP BY 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