2014-10-08 139 views
0

我有一個查詢從表可以包含多個時間的表中得到A.QID。它通常會發生12次,因爲每個月有一次數據導入。TSQL Group By Query

我只需要一次查詢他們的數據,所以我需要在A.QID字段上做DISTINCT,但我遇到了麻煩。

SELECT A.QID, 
      (SELECT TOP 1 E.[FirstName], -- Now we need to figure out who this person is by checking the historical table 
          E.[LastName], 
          E.[NTID], 
          E.[TitleDesc] 
       FROM  employeeTable_historical AS E 
       WHERE E.qid = A.[QID] 
         AND CONVERT (DATE, A.[timestamp]) > CONVERT (DATE, E.[Meta_LogDate]) 
       ORDER BY meta_logDate DESC 
       FOR  XML PATH (''), TYPE, ELEMENTS) 
    FROM  [red].[dbo].[attritionCounts] AS A 
    WHERE A.[mgrQID] = @director -- Search all people managers under this director 
      AND YEAR(CAST (A.[timestamp] AS DATE)) = @year 
    ORDER BY A.lvl 

我試過SELECT DISTINCT(A.QID) ...但沒有工作要麼,得到這個錯誤The xml data type cannot be selected as DISTINCT because it is not comparable.

回答

1

一個簡單的解決方案是你的清單限制不同,你的XML添加到它之前:

SELECT A.QID, 
     (SELECT TOP 1 E.[FirstName], -- Now we need to figure out who this person is by checking the historical table 
         E.[LastName], 
         E.[NTID], 
         E.[TitleDesc] 
      FROM  employeeTable_historical AS E 
      WHERE E.qid = A.[QID] 
        AND CONVERT (DATE, A.[timestamp]) > CONVERT (DATE, E.[Meta_LogDate]) 
      ORDER BY meta_logDate DESC 
      FOR  XML PATH (''), TYPE, ELEMENTS) 
FROM  
     --This is the only part I changed so it is not the full table but the distinct of the 2 columns you need 
     ( 
     SELECT DISTINCT QID, [timestamp] 
     FROM [red].[dbo].[attritionCounts] 
     WHERE [mgrQID] = @director -- Search all people managers under this director 
     AND YEAR(CAST ([timestamp] AS DATE)) = @year 
     ) AS A 
    ORDER BY A.lvl 

編輯:如果時間戳不是唯一的QID,您可以使用ROW_NUMBER()獲取第一個:

SELECT A.QID, 
     (SELECT TOP 1 E.[FirstName], -- Now we need to figure out who this person is by checking the historical table 
         E.[LastName], 
         E.[NTID], 
         E.[TitleDesc] 
      FROM  employeeTable_historical AS E 
      WHERE E.qid = A.[QID] 
        AND CONVERT (DATE, A.[timestamp]) > CONVERT (DATE, E.[Meta_LogDate]) 
      ORDER BY meta_logDate DESC 
      FOR  XML PATH (''), TYPE, ELEMENTS) 
FROM  
     --This is the only part I changed so it is not the full table but the distinct of the 2 columns you need 
     ( 
     SELECT QID, [timestamp] 
     FROM 
      (
      SELECT QID, [timestamp], 
       ROW_NUMBER() OVER(PARTITION BY QID ORDER BY [Timestamp]) Row 
      FROM [red].[dbo].[attritionCounts] 
      WHERE [mgrQID] = @director -- Search all people managers under this director 
       AND YEAR(CAST ([timestamp] AS DATE)) = @year 
      ) Tmp1 
     WHERE Row = 1 
     ) AS A 
    ORDER BY A.lvl 
+0

用這個得到一些錯誤。它不會將任何東西綁定到'A'別名以及'無效的列名'DISINCT'.' – SBB 2014-10-08 21:33:54

+0

我修復了打字錯誤,現在它只是底部選擇沒有綁定到'A' – SBB 2014-10-08 21:37:33

+0

對不起,複製並粘貼您的東西,應該看起來好一點。現在就去。 – Steve 2014-10-08 21:42:11