简体   繁体   中英

How to use union query on the same table and sum (value) in mysql?

I have a table :

OC  Period(MM/YYYY) Ing
CHO 04/01/2016      100
CHO 04/01/2016      200
CHO 04/01/2016      0
CFE 04/01/2016      400
CFE 04/01/2016      350
CFE 04/01/2016      0

I have an SQL query like this:

  (SELECT OC,Ing FROM contacts c where ing > 0)
  UNION ALL
  (SELECT OC,Sum(Ing) FROM contacts c where ing = 0 Group by OC)

I want to get a result like this:

Ref Period(MM/YYYY) Ing
CHO 04/01/2016      100
CHO 04/01/2016      200
CHO 04/01/2016      300
CFE 04/01/2016      400
CFE 04/01/2016      350
CFE 04/01/2016      750
(SELECT c.OC, c.Period, c.Ing FROM contacts c where c.ing > 0)
UNION ALL
(SELECT c.OC, c.Period, Sum(c.Ing) AS Ing FROM contacts c Group by c.OC, c.Period)

You could wrap it in another select from statement if you need to sort the output

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