SQL查询来比较彼此之间的行子集

标签 sql sql-server

我正在寻找一个 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/

相关文章:

sql - 如何在 R 中的 sql 查询中传递函数参数?

sql - 在 Google BigQuery 的一个新列中合并/连接列

sql - 每天找到一个最大值

MySQL:加入未使用的表会增加执行时间吗?

SQL 查找丢失的日期范围

带有逗号分隔结果集的sql server子查询

sql - 批量插入日期时间数据

c# - 通过编辑单元格本身将值从 DataGridView 传递到表

php - MySQL 将查询限制为一个一致的值

sql - 在 SQL 中对分层文本进行排序