简体   繁体   中英

How to use SUM in this situation?

I have the following tables below and their schema:

INV

id, product code, name, ucost, tcost, desc, type, qoh

1,123,CPASS 700,1.00,5.00,CPASS 700 Lorem, COM,5
2,456,Shelf 5,2.00,6.00,Shelf 5 KJ, BR,3

GRP

id,type,desc

1,COM,COMPASS
2,BR,SHELF 

Currently I have a query like this:

SELECT INV.*,GRP.DESCR AS CATEGORY 
FROM INV LEFT JOIN GRP ON INV.TYPE = GRP.TYPE 
WHERE INV.QOH = 0

There is no problems with that query.

Right now,I want to know the SUM of the TCOST of every INV record where their QOH is 0.

In this situation, does that I mean all I have to do is to write a separate query like the one below:

SELECT SUM(TCOST)
FROM INV
WHERE QOH = 0 

Does it make any sense for me to try and combine those two queries as one ?

Mmm, you could maybe use a correlated query, though i'm not sure it's the best approach since I'm not sure I understand what your attempting to do:

SELECT INV.*,
       GRP.DESCR AS CATEGORY ,
       (SELECT SUM(TCOST) FROM INV WHERE QOH=0) as your_sum
FROM INV LEFT JOIN GRP ON INV.TYPE = GRP.TYPE 
WHERE INV.QOH = 0

If you want only one value for the sum() , then your query is fine. If you want a new column with the sum, then use window functions:

SELECT INV.*, GRP.DESCR AS CATEGORY,
       SUM(INV.TCOST) OVER () as sum_at_zero
FROM INV LEFT JOIN
     GRP
     ON INV.TYPE = GRP.TYPE 
WHERE INV.QOH = 0;

It does not make sense to combine the queries by adding a row to the first one, because the columns are very different. A SQL result set requires that all rows have the same columns.

First understand that SUM is the aggregate function hence either you can run the Query like (SELECT SUM(TCOST) FROM INV WHERE QOH=0) as total This will return Sum of TCOST in INV Table for mentioned condition.

Another approach is finding the Sum based on the some column (eg Type)

you could write query like

SELECT Type , SUM(TCOST) FROM INV WHERE QOH=0 GROUP BY type ;

Its not clear on what criteria you want to sum . But I think above two approaches would provide you fare idea .

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