Sql-Server

查詢以獲取每個組的隊列位置

  • March 11, 2016

我有一個包含以下範例數據的隊列表:

id  company location
1   acme    new york
2   acme    philadelphia
3   genco   st.louis
4   genco   san diego
5   genco   san francisco
6   acme    miami

我想查詢每個公司組的隊列位置以顯示每個公司的隊列位置(假設 acme 在 500 Genco 開始之前有 1,000 行,然後在 Genco 記錄過程之後 acme 有 5,000 行)。我想要的結果如下所示:

queuePositionId company
1    acme
3    genco
6    acme

我玩弄了排名和分組,但一個公司組可以在隊列中的任何位置多次出現這一事實一直弄亂我的聚合。我也嘗試了dense_rank但無法弄清楚訂購。有任何想法嗎?

這是一個差距和島嶼問題。有關此類問題的更多詳細資訊,請參見此處

這應該做你需要的:

-- Generate test data
DECLARE @Companies TABLE
(
   ID INT
   ,Company NVARCHAR(100)
   ,Location NVARCHAR(100)
);

INSERT @Companies
SELECT *
FROM    (VALUES (1, 'acme', 'new york')
               ,(2, 'acme', 'philadelphia')
               ,(3, 'genco', 'st.louis')
               ,(4, 'genco', 'san diego')
               ,(5, 'genco', 'san francisco')
               ,(6, 'acme', 'miami')
       ) AS CompanyLocations(ID, Company, Location);

-- Find company positions
;WITH cte_Companies
AS
(
   SELECT ID
          ,Company
          ,CASE 
             WHEN LAG(Company) OVER(ORDER BY ID) = Company  
             THEN 1
             ELSE 0
           END AS CompanyPosition
   FROM @Companies
)

SELECT ID, Company
FROM cte_Companies
WHERE CompanyPosition = 0

更新 Andriy 指出我的解決方案是 SQL Servre 2012+ 解決方案。以下程式碼應該適用於 2005 年之前的版本。

-- Generate test data
DECLARE @Companies TABLE
(
   ID INT
   ,Company NVARCHAR(100)
   ,Location NVARCHAR(100)
);

INSERT @Companies
SELECT *
FROM    (VALUES (1, 'acme', 'new york')
               ,(2, 'acme', 'philadelphia')
               ,(3, 'genco', 'st.louis')
               ,(4, 'genco', 'san diego')
               ,(5, 'genco', 'san francisco')
               ,(6, 'acme', 'miami')
               -- Further test data
               ,(7, 'genco', 'London')
               ,(8, 'genco', 'Portsmouth')
       ) AS CompanyLocations(ID, Company, Location);

-- Find company positions

SELECT ID, Company
FROM @Companies c1
WHERE NOT EXISTS    (
                       SELECT *
                       FROM @Companies c2
                       WHERE c1.Company = c2.Company
                       AND c1.ID - 1 = c2.ID
                   )

引用自:https://dba.stackexchange.com/questions/131916