我有一个SQL Server表[hobbies],如下所示:
id hobby skills organization
-------------------------------------------------------
1 reading encoding greenpeace
2 cooking web design red cross
3 baking programming convoy of hope
我希望查询结果如下:
hobby skills organization
------------------------------------------------
reading programming greenpeace
cooking web design red cross
baking encoding convoy of hope
爱好按升序排序,技能按降序排序,最后组织按升序排序。
有可能吗?
答案 0 :(得分:1)
这是一个非常奇怪的数据组织,但如果你坚持,可以使用ROW_NUMBER
函数来完成。
示例数据 - 我添加了您在评论中提到的employeenumber
。
DECLARE @T TABLE (
id int,
hobby nvarchar(255),
skills nvarchar(255),
organization nvarchar(255),
employeenumber int);
INSERT INTO @T VALUES
(11, 'reading', 'encoding ', 'greenpeace ', 123),
(12, 'cooking', 'web design ', 'red cross ', 123),
(13, 'baking ', 'programming', 'convoy of hope', 123),
(21, 'reading', 'encoding ', 'greenpeace ', 222),
(22, 'cooking', 'web design ', 'red cross ', 222),
(23, 'baking ', 'programming', 'convoy of hope', 222);
<强>查询强>
WITH
CTE
AS
(
SELECT
id
,hobby
,skills
,organization
,ROW_NUMBER() OVER (ORDER BY id ASC) AS rn_asc
,ROW_NUMBER() OVER (ORDER BY id DESC) AS rn_desc
FROM @T AS hobbies
WHERE employeenumber = 222
)
SELECT
C1.id
,C1.hobby
,C2.skills
,C1.organization
FROM
CTE AS C1
INNER JOIN CTE AS C2 ON C2.rn_desc = C1.rn_asc
ORDER BY C1.rn_asc;
<强>结果强>
+----+---------+-------------+----------------+
| id | hobby | skills | organization |
+----+---------+-------------+----------------+
| 21 | reading | programming | greenpeace |
| 22 | cooking | web design | red cross |
| 23 | baking | encoding | convoy of hope |
+----+---------+-------------+----------------+
答案 1 :(得分:0)
这不是表的工作方式。你的每个元组(id,业余爱好,技能,组织)构成一排。您可以更改(整个)行的顺序,但不能在任意条件下单独对列进行排序。
答案 2 :(得分:0)
这不是表的工作方式,但可以实现这一点。一种方法是聚合和union all
:
select max(hobby) as hobby, max(skills) as skills,
max(organization) as organization
from ((select row_number() over (order by id asc) as seqnum, hobby, NULL as skills, organization
from hobbies
) union all
(select row_number() over (order by id desc), NULL, skills, NULL
from hobbies
)
) h
group by seqnum
order by seqnum;