2014-10-08 121 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