SQL Server: Performing OUTER APPLY between two subqueries

时间:2018-11-23 13:26:35

标签: sql-server sql-server-2008 sql-server-2008-r2

I want to get results from two subqueries using an OUTER Apply but it does not work. Below I put the skeleton of the query i am trying to do as an example:

SELECT DISTINCT D.Field1, D.Field2, S.Field1, S.Field2
FROM (
        SELECT Field1, Field2
        FROM Table1 t1 INNER JOIN Table2 t2 on t1.CommonField = t2.CommonField
                       INNER JOIN Table3 t3 on t3.CommonField = t2.CommonField
                       LEFT JOIN Table4 t4 on t4.CommonField = t3.CommonField
        WHERE t1.Date > '20181011'

     ) D OUTER APPLY
     (
        SELECT Field1, Field2
        FROM Table5 t5 INNER JOIN Table6 t6 on t6.CommonField = t5.CommonField
                       INNER JOIN Table7 t7 on t7.CommonField = t6.CommonField
        WHERE t5.Field4 = 'SomeWhat'
        GROUP BY t5.Date
     ) S

SQL Server parser give me an error: Icorrect syntax near 'D'.

I am using SQL Server 2008.

1 个答案:

答案 0 :(得分:0)

除了使用GROUP BY t5.Date,但选择其他列,例如Field1, Field2之外,代码看起来还不错。只需将这些列添加到GROUP BY

SELECT Field1, Field2
FROM Table5 t5 INNER JOIN Table6 t6 on t6.CommonField = t5.CommonField
INNER JOIN Table7 t7 on t7.CommonField = t6.CommonField
WHERE t5.Field4 = 'SomeWhat'
GROUP BY t5.Date, t5.Field1, t5.Field2

让我展示一个工作示例:

DECLARE  @TableA TABLE (
  id BIGINT IDENTITY NOT NULL,
  value nvarchar(max) NOT NULL
);

DECLARE  @TableB TABLE (
  id BIGINT IDENTITY NOT NULL,
  value nvarchar(max) NOT NULL,
  tableARid BIGINT NOT NULL
)

INSERT INTO @TableA(value) VALUES('test');
INSERT INTO @TableB(value, tableARid) VALUES ('test1', 1);
INSERT INTO @TableB(value, tableARid) VALUES ('test2', 1);
INSERT INTO @TableB(value, tableARid) VALUES ('test3', 1);

SELECT
  subQuery.id
, subQuery.value
, oa.id
FROM 
(
    SELECT 
      ta.id
    , ta.value
    FROM @TableA ta
) subQuery
OUTER APPLY 
(
   SELECT 
     tb.id
   , tb.value 
   FROM @TableB tb   
   GROUP BY tb.id, tb.[value]
) oa