Select Statement

时间:2015-11-13 13:16:47

标签: sql sql-server

我遇到了以下查询的问题。

我有四张桌子:

OBGT - T0
OACT- T1
OBGS - T2
OASC - T3

我的疑问是:

SELECT *FROM (
SELECT DISTINCT
    concat([Segment_0], '-' , [Segment_1], '-',[Segment_2])  As [AcctCode],
    T1.[AcctName],
    T2.[Name],
    concat(T3.[Code],'-',T3.[Name]),T0.[DebLTotal] AS [ANNUAL BUDGET],
    (SELECT concat(T3.Code , '-', T3.[Name]) where T3.SegmentId = '1') AS [Project],
    (SELECT concat(T3.Code , '-', T3.[Name]) where T3.SegmentId = '2') AS [Distt]
FROM OBGT T0
    INNER JOIN OACT T1 ON T0.[AcctCode] = T1.[AcctCode]
    INNER JOIN OBGS T2 ON T0.[Instance] = T2.[AbsId] 
    INNER JOIN OASC T3 ON (T3.SegmentId = '1' AND T3.Code = [Segment_1])
                       OR (T3.SegmentId = '2' AND T3.Code = [Segment_2])

) AS d

WHERE Distt =' 001' 所以在这个查询中:

  • OASC - T3表的字段SegmentId有两个Id 1和2
  • OACT - T0表有两个字段Segment_1(值与SegmentId = 1匹配)和Segment_2(值与SegmentId = 2匹配)。

您可以签入查询。

但如果我提出一个条件,问题就会出现。

where Project = 100正在运行,但如果条件为where Project = 100 and Distt = 001,则会收到错误消息:

  

Msg 207,Level 16,State 1,Line 11
  列名称无效' Distt'。

2 个答案:

答案 0 :(得分:2)

将原始查询作为派生表:

var duck = Object.assign(Object.create(animal), {
    speak : function () { 
        console.log("quack");
        return this;
    }
});

duck.move(6, 7).locate().speak();

注意:您需要为每列添加列名/别名才能使用它!

答案 1 :(得分:1)

在您创建表达式的SELECT子句中,您创建了一个列别名,{expression}[Alias]

为了解决您的问题,您需要使用派生表(见下文),其次是不使用单引号作为列别名 - 使用方括号。

SELECT *
FROM (
    SELECT DISTINCT
        concat([Segment_0], '-' , [Segment_1], '-',[Segment_2])  As [AcctCode],
        T1.[AcctName],
        T2.[Name],
        concat(T3.[Code],'-',T3.[Name]),T0.[DebLTotal] AS 'ANNUAL BUDGET',
        (SELECT concat(T3.Code , '-', T3.[Name]) where T3.SegmentId = '1') AS [Project],
        (SELECT concat(T3.Code , '-', T3.[Name]) where T3.SegmentId = '2') AS [Distt]
    FROM OBGT T0
        INNER JOIN OACT T1 ON T0.[AcctCode] = T1.[AcctCode]
        INNER JOIN OBGS T2 ON T0.[Instance] = T2.[AbsId] 
        INNER JOIN OASC T3 ON (T3.SegmentId = '1' AND T3.Code = [Segment_1])
                           OR (T3.SegmentId = '2' AND T3.Code = [Segment_2])

    ) AS d
WHERE Distt = 001

请注意,如果SELECT子句上的子查询返回超过1行,您的查询可能会遇到另一个问题!您的查询将给出另一个错误。

项目有效,因为它可能是其中一个表中的一列。