检索特定行时,“子查询返回多个结果”错误

时间:2014-04-03 09:27:06

标签: sql sql-server-2008

我正在尝试从临时表中获取指定的行。以下是我的代码:

Select 
        t.pub_id, m.KEY_DATE_VALUE
INTO
        #temp1
FROM 
        #temp t
        JOIN CUSTOM_META m
ON 
        t.pub_id = m.ITEM_ID
        AND m.KEY_NAME = 'ArticleDate'
ORDER BY 
        m.KEY_DATE_VALUE DESC 

Select * from #temp1

显示器:

154477  2014-03-03 20:56:00.000
155001  2014-03-03 18:00:00.000
155000  2014-03-03 17:57:00.000
154999  2014-03-03 17:55:00.000
154998  2014-03-03 17:52:00.000
154463  2014-03-03 16:45:10.000
154461  2014-03-03 16:41:11.000

但是在做:

Select pub_id from( select pub_id, Row_Number() over (order by pub_id) as 
item_number from #temp1) AS mYtABLE WHERE mYtABLE.item_number BETWEEN 1 AND 5

项目的顺序发生变化。

如何修改第二个语句,以使订单保持原样。

1 个答案:

答案 0 :(得分:0)

试试这个

Select pub_id,KEY_DATE_VALUE DESC
INTO
        #temp1
FROM 
        (
        select pub_id, Row_Number() over (order by pub_id desc) as 
        item_number from #temp) AS mYtABLE WHERE mYtABLE.item_number BETWEEN 1 AND 9
    ) t
        JOIN CUSTOM_META m
ON 
        t.pub_id = m.ITEM_ID
        AND m.KEY_NAME = 'ArticleDate'
ORDER BY 
        m.KEY_DATE_VALUE DESC 

按KEY_DATE_VALUE DESC排序结果集,如下所示

select pub_id from #temp1
order by KEY_DATE_VALUE DESC