子查询中的sql server语法错误

时间:2014-10-02 19:06:49

标签: sql sql-server database

我正在努力获得客户的最后状态。通过浏览示例,我将这个查询放在一起工作:

SELECT table.Card, 
    table.Type, 
    table.Date, 
    ROW_NUMBER() OVER   
        (PARTITION by table.CARD ORDER BY table.date DESC, table.TYPE, table.DATE) rn 
 FROM table 
 WHERE table.Type = 'active' or table.Type = 'erased'

从那里,我只需要那些rn = 1的记录,但是一旦我尝试使用它作为子查询,如下所示,我得到一个syntaxis错误:

SELECT * FROM (
    SELECT table.Card, 
        table.Type, 
        table.Date, 
        ROW_NUMBER() OVER   
            (PARTITION by table.CARD ORDER BY table.date DESC, table.TYPE, table.DATE) rn 
     FROM table 
     WHERE table.Type = 'active' or table.Type = 'erased'
) WHERE rn=1

这一定很简单,我只是想念,但我完全糊涂了。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

您应该为INNER选择指定别名。试试这个。

SELECT * FROM (
    SELECT table.Card, 
        table.Type, 
        table.Date, 
        ROW_NUMBER() OVER   
            (PARTITION by table.CARD ORDER BY table.date DESC, table.TYPE, table.DATE) rn 
     FROM table 
     WHERE table.Type = 'active' or table.Type = 'erased'
) foo WHERE rn=1