问题
I have the following query :
SELECT SUM(P_QTY)
FROM rankhistory
WHERE P_ID= '1'
AND RH_DATE>=1438556400
AND RH_DATE<1438642800
The above query returns 268
The result set contains two elements of P_QTY which are 160
and 108
Now what I want is be able to receive the difference instead of the sum, so what I want my query to return is 52
, how can I achieve that through sql query?
Please note that the subquery can return more than one result, and the intended is get the total change. For example if query returns 168
160
150
, the result should be 18
.
回答1:
There's no aggregate function for difference, but since you know exactly which rows to use, you can select each value as its own subquery, then subtract the two columns from one another in a single select statement.
SELECT a.op, b.op, a.op - b.op as diff
FROM (SELECT 10 as op) a
JOIN (SELECT 8 as op) b
Expressed in accordance with your schema, it would probably look like this:
SELECT a.op, b.op, a.op - b.op as diff
FROM (SELECT P_QTY as op FROM rankhistory WHERE P_QTY = 160) a
JOIN (SELECT P_QTY as op FROM rankhistory WHERE P_QTY = 108) b
To use this approach regularly in an application, however, you'll want to handle it based on ID's or something else easily selectable and meaningful.
It sounds like you want something else, though. Perhaps you're interested in the difference between max and min during a date range?
SELECT MAX(P_QTY) - MIN(P_QTY) as diff
FROM rankhistory
WHERE rh_date BETWEEN '1438556400' AND '1438642800'
来源:https://stackoverflow.com/questions/31908943/mysql-get-difference-instead-of-sum