简体   繁体   中英

How to sort & group by sql query?

I have Data

id Date      CatId  itemid itemname price
1  10/5/2019  1         1      ABC        20
2  10/5/2019  1         2      XYZ        30
3  10/5/2019  2         1      ABC        20
4  10/5/2019  3         1      ABC        20  

5  11/5/2019  1         2      XYZ        30
6  11/5/2019  2         1      ABC        20
7  11/5/2019  2         3      PQR        40

8  12/5/2019  3         1      ABC        20
9  12/5/2019  3         2      XYZ        30 
10  12/5/2019  1         2      XYZ        30
11  12/5/2019  2         1      ABC        20

expected result data

date            CatId   toal 
 10/5/2019      1           50
 10/5/2019      2           20
 10/5/2019      3           20

  11/5/2019     1       30
  11/5/2019     2       60
  12/5/2019     1       30
  12/5/2019     2       20
  12/5/2019     3       50

I want result order by date and after sum of price group by catid,

I have tried multiple query applied but get exact solution. I have spent so much time.

I have tried bellow queries

SELECT * FROM (SELECT * FROM `table`  ORDER BY `date` DESC) as tbl
 GROUP BY tbl.`catid`

SELECT *
FROM `table` 
GROUP BY `date` ORDER BY `date` DESC

SELECT * 
FROM (
    SELECT * FROM `table`  
    ORDER BY `date` DESC
) AS sub
GROUP BY `catid` ORDER BY `date` DESC

the columns you can use in order by and group by can be different

You could use group by and sum directly

select date, catid, sum(price)
from my_table 
group by date, catid
order by date, sum(price), catid

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