每个标识符只有月末值

时间:2017-05-31 18:46:27

标签: sql

对于下面的代码,我试图仅为所有独特的FundId选择月末值。下面的代码一直给我错误

Msg 164,Level 15,State 1,Line 16 每个GROUP BY表达式必须至少包含一个不是外部引用的列。

如何修复where语句以提取每个基金的所有月末值

SELECT TOP 10000 a.[PerformanceId]
      ,[InvestmentType]
      ,[EndDate]
      ,a.[CurrencyId]
      ,[AssetValue]
      ,c.FundId
  FROM [StatusData_DMWkspaceDB].[dbo].[NetAssetsValidationFailure] a
  LEFT JOIN MappingData_GAPortDB.dbo.PerformanceLevelMapping b
  ON a.PerformanceId = b.PerformanceId
  LEFT JOIN MappingData_GAPortDB.dbo.FundClassMatching c
  ON b.SecId = c.SecId
  WHERE a.EndDate IN (
    SELECT MAX(a.EndDate)
    From [StatusData_DMWkspaceDB].[dbo].[NetAssetsValidationFailure]
    GROUP BY c.FundId, Month(a.EndDate), YEAR(a.EndDate))

1 个答案:

答案 0 :(得分:1)

这是您的查询:

SELECT TOP 10000 navf.[PerformanceId], [InvestmentType], [EndDate],
       navf.[CurrencyId], [AssetValue], fcm.FundId
FROM [StatusData_DMWkspaceDB].[dbo].[NetAssetsValidationFailure] navf LEFT JOIN
     MappingData_GAPortDB.dbo.PerformanceLevelMapping plm
     ON navf.PerformanceId = plm.PerformanceId LEFT JOIN
     MappingData_GAPortDB.dbo.FundClassMatching fcm
     ON l.m.SecId = fcm.SecId
WHERE navf.EndDate IN (SELECT MAX(navf.EndDate)
                       From [StatusData_DMWkspaceDB].[dbo].[NetAssetsValidationFailure] navf
                       GROUP BY fcm.FundId, Month(navf.EndDate), YEAR(navf.EndDate)
                     );

学习使用合理的表别名,这样查询就更容易编写和阅读。

在任何情况下,您的WHERE子句仅引用GROUP BY中的外部表。信息很清楚。

我甚至不确定你想做什么,但我猜这是你想要的工作版本:

SELECT x.*
FROM (SELECT navf.[PerformanceId], [InvestmentType], [EndDate],
             navf.[CurrencyId], [AssetValue], fcm.FundId,
             ROW_NUMBER() OVER (PARTITION BY fcm.FundId, Month(navf.EndDate), YEAR(navf.EndDate)
                                ORDER BY navf.EndDate DESC
                               ) as seqnum
      FROM [StatusData_DMWkspaceDB].[dbo].[NetAssetsValidationFailure] navf LEFT JOIN
           MappingData_GAPortDB.dbo.PerformanceLevelMapping plm
           ON navf.PerformanceId = plm.PerformanceId LEFT JOIN
           MappingData_GAPortDB.dbo.FundClassMatching fcm
           ON l.m.SecId = fcm.SecId
     ) x
WHERE seqnum = 1;