MS SQL,子查询中的外部列

时间:2017-08-08 07:36:55

标签: sql-server subquery cross-apply

给出这个表定义:

CREATE TABLE Attivita_T041(Kint_TP013_IdAttivita INT)

CREATE TABLE TP004_LinkPersonaArea
    (int_T013_IdArea int, 
     dte_T013_DataInizio date, 
     dte_T013_DataFine date, 
     int_T013_IdPersona int, 
     int_T013_IdRuoloArea int)
go


CREATE TABLE [dbo].[Q_TP013_Pianificazione] (
    [Kint_TP013_IdAttivita]      INT     ,
    [Ksin_TP013_IdArea]          SMALLINT,
    [Ksin_TP013_AnnoRifPian]     SMALLINT,
    [sin_TP013_Giorni]           SMALLINT   
);

我需要一个带有查询的表函数,该查询将Attivita_T041表与许多其他表连接起来,现在我必须添加一个子查询来获取两个信息:[sin_TP013_Giorni]的总数和{{1}的总数[sin_TP013_Giorni]当前用户实际工作的地方(从[Ksin_TP013_IdArea]读取)

这是查询的这一部分:

TP004_LinkPersonaArea

但是我无法做到这一点,因为SELECT .... FROM Attivita_T041 INNER JOIN ---- many other tables here LEFT OUTER JOIN PersonaArea_T013 ON int_T013_IdPersona = @idUtente AND dte_T013_DataInizio <= @dataRiferimento AND (dte_T013_DataFine > @dataRiferimento OR dte_T013_DataFine IS NULL) LEFT OUTER JOIN ( SELECT Kint_TP013_IdAttivita , SUM(sin_TP013_Giorni) AS GiorniPianificatiAnno , SUM(CASE WHEN Ksin_TP013_IdArea = int_T013_IdArea THEN sin_TP013_Giorni ELSE 0 END) AS GiorniPianificatiAnnoArea FROM Q_TP013_Pianificazione INNER JOIN dbo.FN_DettaglioPianificazione(YEAR(@dataRiferimento), 0) ON Progressivo = Ktyi_TP013_ProgressivoPian WHERE Ksin_TP013_AnnoRifPian = YEAR(@dataRiferimento) GROUP BY Kint_TP013_IdAttivita ) AS Pianificazione ON Kint_TP013_IdAttivita = Kint_T041_IdAttivita 列已经超出了子查询

搜索SO我发现使用int_T013_IdArea的建议,所以我切换到这个:

OUTER APPLY

但现在我收到了这个错误:

  

在包含的聚合表达式中指定了多个列   外部参考。如果聚合的表达式包含   外部引用,那么外部引用必须是唯一的列   在表达式中引用。

有办法吗?

0 个答案:

没有答案