简体   繁体   中英

MySql: select total grouped by two columns

I have a table transactions like this: http://prntscr.com/aa5vg6 I want to select total amount group by purpose and date column. Such as: found 10 records for purpose 1, 21 records for purpose 2 and so on... in the date 2016-02-01, 2016-02-05 and so on... the result should be total sum of purpose and the purpose total should be grouped by date.

I tried this query, but it fails grouping the date while multiple purpose found in same date:

SELECT SUM(amount) totalAmount FROM `transactions` WHERE purpose IN(1,2,12) GROUP BY date ORDER BY date DESC

You should group by date and purpose in that case:

SELECT
    DATE(`date`) date,
    `purpose`,
    COUNT(`purpose`) purposeCount,
    SUM(`amount`) totalAmount
FROM
    `transactions`
WHERE
    `purpose` IN (1, 2, 12)
GROUP BY
    DATE(`date`),
    `purpose`
ORDER BY
    DATE(`date`) DESC

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