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

时间:2015-11-11 22:10:49

标签: 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
                                                  ...

5 个答案:

答案 0 :(得分:3)

一种方法是条件聚合。对于每种产品:

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只对每个产品出现一次。鉴于您的数据,这似乎是合理的。

答案 1 :(得分:1)

相当直截了当。获取公司XY的产品价格。将他们加入产品并比较价格。

它假定每个产品都为公司列出一次。

WITH
CTE_X
AS
(
    SELECT Product, Price
    FROM T
    WHERE Company = 'X'
)
,CTE_Y
AS
(
    SELECT Product, Price
    FROM T
    WHERE Company = 'Y'
)
SELECT COUNT(*) AS cc
FROM
    CTE_X
    INNER JOIN CTE_Y ON CTE_Y.Product = CTE_X.Product
WHERE
    CTE_Y.Price > CTE_X.Price
;

答案 2 :(得分:1)

您可以使用条件聚合执行此操作。

with xandy as (select product, 
               max(case when company = 'X' then price end) as xprice,
               max(case when company = 'Y' then price end) as yprice
               from tablename
               group by product)
select count(*)
from xandy
where yprice > xprice

答案 3 :(得分:1)

您可以使用:

SELECT COUNT(*)
FROM (
  SELECT Product
  FROM mytable
  GROUP BY Product
  HAVING MAX(CASE WHEN Company = 'Y' THEN Price END) 
         > 
         MAX(CASE WHEN Company = 'X' THEN Price END) ) AS t

子查询返回公司Y比公司X贵的产品列表。外部查询只计算这些产品的数量。

使用窗口函数的另一个版本:

SELECT COUNT(*)
FROM (
  SELECT Company, 
         ROW_NUMBER() OVER (PARTITION BY Product 
                            ORDER BY Price DESC) AS rn
  FROM mytable 
  WHERE Company IN ('X', 'Y')) AS t
WHERE t.rn = 1 AND Company = 'Y'

子查询会过滤掉'X''Y'作为Company的所有行。外部查询计算Company = 'Y'具有最高价格的行数。

答案 4 :(得分:1)

这个查询效率不高,会为您提供所需内容的详细信息:

Select 
  CompanyY.*,
  CompanyX.*
FROM 
(
  select * from OrderDetails
  where Company = 'Y'
) CompanyY
JOIN
(
  select * from OrderDetails
  where Company = 'X'
) CompanyX
ON CompanyX.Product = CompanyY.Product
WHERE CompanyY.Price > CompanyX.Price

尝试使用SQLFiddle Here