我正在寻找一个 SQL 查询(在 SQL Server 中)。我需要计算 Y 公司比 X 公司更贵的情况。我将如何开始解决这个问题?我查看了各种示例,但找不到任何类似的东西。我看到 PARTITION BY 可能会有帮助,但不确定如何从那里开始 - 任何提示都会非常有帮助。
ReadingId | Product | Price | Company
----------------------------------------------
1 | A | 3 | X
2 | A | 4 | Y
3 | A | 5 | Z
4 | B | 11 | X
5 | B | 12 | Y
6 | B | 13 | Z
...
最佳答案
一种方法是条件聚合。对于每个产品:
select product,
max(case when company = 'Y' then price end) as Yprice
max(case when company = 'X' then price end) as Xprice
from t
group by product;
为了计数,您可以执行以下操作:
select count(*)
from (select product,
max(case when company = 'Y' then price end) as Yprice
max(case when company = 'X' then price end) as Xprice
from t
group by product;
) p
where Yprice > Xprice;
还有其他方法。可以使用 Pivot
,以及带有聚合的 join
:
select count(*)
from t ty join
t tx
on ty.company = 'Y' and tx.company = 'X' and ty.product = tx.product
where ty.price > tx.price;
我应该指出,所有这些方法都假设 X 和 Y 对每个产品只出现一次。鉴于您的数据,这似乎是合理的。
关于SQL查询来比较彼此之间的行子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33660815/