簡體   English   中英

用於比較彼此之間的行子集的SQL查詢

[英]SQL query to compare subsets of rows between each other

我之后有一個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只對每個產品出現一次。 鑒於您的數據,這似乎是合理的

相當直截了當。 獲取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
;

您可以使用條件聚合執行此操作。

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

您可以使用:

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'具有最高價格的行數。

此查詢效率不高,將為您提供所需內容的詳細信息:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM