编写查询以按升序和降序显示字段

时间:2015-08-26 05:35:18

标签: sql-server

我在接受采访时遇到过这种情况。表设计包含单个整数值字段。编写查询以按升序和降序显示字段

3 个答案:

答案 0 :(得分:0)

假设您有一个名为tbl的表,其列名value的类型为int,请使用Order by子句获取升序和降序值

按升序排列:

SELECT value FROM tbl ORDER BY value ASC

并按降序排列:

SELECT value FROM tbl ORDER BY value DESC

答案 1 :(得分:0)

您可以使用awk '{ for(i=1;i<=3;i++) print $1" "substr($2,5*(i-1)+1,5) >> "file"i".txt" }' inputfilename

来实现此目的
ROW_NUMBER

<强> RESULT

CREATE TABLE tbl(N INT)
INSERT INTO tbl VALUES
(1),(2),(3),(4),(5),(6),(7),(8),(9),(10);

WITH Cte AS(
    SELECT *,
        rn_a = ROW_NUMBER() OVER(ORDER BY N ASC),
        rn_d = ROW_NUMBER() OVER(ORDER BY N DESC)
    FROM tbl
)
SELECT 
    Ascending = a.N, 
    Descending = b.N
FROM Cte a
INNER JOIN Cte b
    ON b.rn_d = a.rn_a

DROP TABLE tbl

答案 2 :(得分:0)

试试这个:

select a.num,b.num from 
(select a.num, row_number() over (order by num) as rnum  from nums a) a
join (select a.num, row_number() over (order by num desc) as rnum  from nums a) b on a.rnum = b.rnum;