没有为't'T_SQL错误的第2列指定列名

时间:2014-01-13 06:06:58

标签: sql

我想从这个T-SQL只返回debtorid。它给出了错误“ 没有为't'的第2列指定列名。“我的查询在下面。

 with t as 
(SELECT debtorid,MAX(dbo.FollowUp.followupdate) FROM dbo.FollowUp WITH (NOLOCK) WHERE
( dbo.FollowUp.FollowUpDate >= '01-01-2011 00:00:00:000' and dbo.FollowUp.FollowUpDate <= '01-13-2014 23:59:59.000'
and Status = 'PTP')  GROUP BY [Status], DebtorId)

SELECT t.debtorid FROM t;

凭借我的小知识,我认为上述应该适合我。然而,它没有。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

您需要为第二列添加名称,例如:

with t as 
(SELECT debtorid, MAX(dbo.FollowUp.followupdate) maxFollowup 
 FROM dbo.FollowUp WITH (NOLOCK) 
 WHERE dbo.FollowUp.FollowUpDate >= '01-01-2011 00:00:00:000' 
       and dbo.FollowUp.FollowUpDate <= '01-13-2014 23:59:59.000'
       and Status = 'PTP'
GROUP BY [Status], DebtorId)

SELECT t.debtorid FROM t;

答案 1 :(得分:1)

您正在使用Common Table Expressions或CTE,在CTE中,您必须具有msdn列名称。您还可以参考CTE最佳实践:

http://technet.microsoft.com/en-us/library/ms190766(v=sql.105).aspx http://blog.sqlauthority.com/2011/05/10/sql-server-common-table-expression-cte-and-few-observation/

;with t as 
(
    SELECT FWP.debtorid
        ,MAX(FWP.followupdate) followupdate 
    FROM dbo.FollowUp  FWP WITH (NOLOCK) 
    WHERE
    ( 
        FWP.FollowUpDate >= '01-01-2011 00:00:00:000' 
         and FWP.FollowUpDate <= '01-13-2014 23:59:59.000'
         and FWP.Status = 'PTP'
    )  GROUP BY FWP.[Status], FWP.DebtorId
)
SELECT t.debtorid FROM t;