简体   繁体   中英

Adding two SUM DISTINCT values, MySQL

I am using the following query to gathering and SUM info about some specific data in my MySQL table:

SELECT rowid,
    id_name,
    SUM(DISTINCT colA) AS colAtotal,
    SUM(DISTINCT colB) AS colBtotal
FROM orders

I know I can add colAtotal and colBtotal together with PHP after the query, but I need 'total' column to build by sort with in the query.

How can I add '(SUM(DISTINCT colA) as colAtotal, SUM(DISTINCT colB) as colBtotal)' together in the query so I will have another column for my sort?

Thanks

Just add them up.

SELECT 
    SUM(DISTINCT colA) AS colAtotal,
    SUM(DISTINCT colB) AS colBtotal,
    SUM(DISTINCT colA) + SUM(DISTINCT colB) AS colAplusBtotal
FROM orders

You can remove the separate sums if you don't need them

SELECT 
    SUM(DISTINCT colA) + SUM(DISTINCT colB) AS colAplusBtotal
FROM orders

Or if you want to sort by it:

Just add them up.

SELECT 
    SUM(DISTINCT colA) AS colAtotal,
    SUM(DISTINCT colB) AS colBtotal
FROM orders
ORDER BY  
    SUM(DISTINCT colA) + SUM(DISTINCT colB)

Note, there is no column alias when you add it in ORDER BY. Since the field is not returned, it wouldn't make sense to give it an alias.

I've removed the other (non-aggregated) fields, since you're not grouping by them. Keeping them might just confuse you, since they are basically random values.

Note though, that DISTINCT may not do what you expect. This formula adds up all different order amounts, provided that colA and colB are amounts. So if you have one million orders, but they all happen to have values of either 10 or 17 then the result of such a sum will be 27 , since only the unique values are added up.

I can't look in your head, of course, but I expect you seek something like this, to get the total amount per customer or something:

SELECT 
    Customer,
    SUM(colA) AS colAtotal,
    SUM(colB) AS colBtotal
FROM orders
GROUP BY Customer
ORDER BY 
    SUM(colA) + SUM(colB)

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