简体   繁体   English

SQL:如何比较同一列中两行的对应值?

[英]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. 如果要返回任何人的数量之和,则应使用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. 如果要比较两个以上的产品,则查询必须使用group by。 Answer of @Loser is good for your question so far. 到目前为止,@ Loser的答案很适合您的问题。 Maybe you should give us more detail of your expected result. 也许您应该给我们更多您预期结果的细节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM