如何使用此SQL语句执行左侧或子查询?

时间:2015-11-05 21:01:54

标签: sql sql-server

我有一些left join因此我想在我的其他查询中添加/合并此sql

SELECT
    A.ID
FROM 
    Table1 as A 
LEFT JOIN
    (SELECT 
         T.ID, T.TRF_TAKEN,
         SUM(CASE WHEN CAST([UNT_TRNSFER] AS FLOAT) = 0 
                  THEN CAST([TRF_TAKEN] AS FLOAT) 
                  ELSE ISNULL([UNT_TRNSFER], 0) 
             END) AS 'UNT_TRNSFER'
     FROM TRNS_C as T
     GROUP BY ID;) ON A.ID = TransfC.ID
WHERE
    A.ID = 1;

ERROR

  

列'TRNS_C.TRF_TAKEN'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

3 个答案:

答案 0 :(得分:1)

您只需将非聚合字段放入GROUP BY即可。您要求它按EMPLID分组,但您只选择t.ID和t.TRF_Taken。

select A.ID
from Table1 as A 

LEFT JOIN (
    SELECT T.ID, T.TRF_TAKEN,
            SUM(CASE WHEN CAST([UNT_TRNSFER] AS FLOAT) = 0 THEN CAST([TRF_TAKEN] AS FLOAT) ELSE ISNULL([UNT_TRNSFER], 0) END) AS 'UNT_TRNSFER'
            FROM TRNS_C as T
            GROUP BY T.ID, T.TRF_TAKEN;
    ) Transfc
ON A.ID = TransfC.ID
    Where A.ID = 1;

答案 1 :(得分:1)

;移除GROUP BY ID;),将T.TRF_TAKEN添加到GROUP BY子句,然后添加您加入的表别名Transfc

SELECT A.ID, Transfc.UNT_TRNSFER
FROM Table1 AS A 
LEFT JOIN (
    SELECT  T.ID, T.TRF_TAKEN,
            SUM(CASE WHEN CAST([UNT_TRNSFER] AS FLOAT) = 0 THEN CAST([TRF_TAKEN] AS FLOAT)
            ELSE ISNULL([UNT_TRNSFER], 0) END) AS 'UNT_TRNSFER'
            FROM TRNS_C as T
            GROUP BY T.ID, T.TRF_TAKEN
) Transfc
ON A.ID = TransfC.ID
WHERE A.ID = 1;

答案 2 :(得分:0)

请注意,您问题中的查询可能等同于:

SELECT A.ID
FROM Table1 A 
WHERE A.ID = 1;

left join唯一可能做的就是乘以行数。这似乎不太可能。