简体   繁体   中英

SQL: how to compare corrosponding values two rows from same column?

I have two tables:

VendorTrading;
id  date
1   01-01-2015
2   01-01-2015

CustomerProducts;
id tradeID ProductName Quantity
1  1       XYZ         20
2  2       ABC         30

I need to make comparison of two product's quantity, of names will be given as parameters, on a particular date. here is my query so far,

Select sum(Cp.ProductQuantity) 
FROM VendorTrading VT inner join CustomerProducts CP on VT.Id = CP.VendorTradingId
WHERE  CP.ProductName = ISNULL ('XYZ', CP.ProductName) and VT.Tradedate = isnull('2015-01-20',VT.Tradedate)

which only returns sum of anyone's quantity. How can I achieve that result? I need to put them on a graph in crystal report. Further more I need to vice versa of same thing but with Two dates but one particular product.

If you want to return sum of anyone's quantity, you should use group by.

Select CP.ProductName,sum(Cp.ProductQuantity) 
FROM VendorTrading VT inner join CustomerProducts CP 
ON VT.Id = CP.VendorTradingId
WHERE  CP.ProductName = ISNULL('XYZ', CP.ProductName)
AND VT.Tradedate = isnull('2015-01-20',VT.Tradedate)
AND CP.ProductName in ('xyz','abc')
GROUP BY CP.ProductName

If you want compare more than 2 products, the query must be use group by. Answer of @Loser is good for your question so far. Maybe you should give us more detail of your expected result.

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