日期:2014-05-18  浏览次数:20649 次

表的某个字段按需排序(快速结贴)
原始数据为:
[code =SQL]
Uid(varchar) uname result
00EF 张三 Approving
76A1 马六 created
7EAC 钱七 Apprved succeed
5BA4 李五 decline
4A87 王四 deleted
[/code]

想要对result字段进行排序,显示顺序优先级为(created->decline->Apprved succeed->Approving->deleted)

即想要结果:
[code =SQL]
Uid uname result
76A1 马六 created
5BA4 李五 decline
7EAC 钱七 Apprved succeed
00EF 张三 Approving
4A87 王四 deleted
[/code]

请问SQL如何写呢?(使用 [code =SQL]order by case result when....end [/code] ?)



------解决方案--------------------
SQL code

DECLARE @tab TABLE([Uid] VARCHAR(10),uname VARCHAR(10),result VARCHAR(20))
DECLARE @t TABLE (id INT ,[DESC] VARCHAR(20))
INSERT INTO @tab
SELECT '00EF', '张三', 'Approving' UNION ALL
SELECT '76A1', '马六', 'created' UNION ALL
SELECT '7EAC', '钱七', 'Apprved succeed' UNION ALL
SELECT '5BA4', '李五', 'decline' UNION ALL
SELECT '4A87', '王四', 'deleted' 
INSERT INTO @t
SELECT 1,'created' UNION ALL
SELECT 2,'decline' UNION ALL
SELECT 3,'Apprved succeed' UNION ALL
SELECT 4,'Approving' UNION ALL
SELECT 5,'DELETED' 
SELECT t1.* FROM @tab t1 INNER JOIN @t t2 ON t1.result=t2.[DESC] ORDER BY t2.id
/*
Uid        uname      result
---------- ---------- --------------------
76A1       马六         created
5BA4       李五         decline
7EAC       钱七         Apprved succeed
00EF       张三         Approving
4A87       王四         deleted
*/

------解决方案--------------------
SQL code

IF EXISTS (SELECT 1 FROM SYSOBJECTS WHERE name = 'tba')
BEGIN
    DROP TABLE tba
END
GO
CREATE TABLE tba
( Uid varchar(10),
  uname VARCHAR(10),
  result VARCHAR(20))
  
INSERT INTO tba
SELECT '00EF', '张三', 'Approving' UNION
SELECT '76A1', '马六', 'created' UNION
SELECT '7EAC', '钱七', 'Apprved succeed' UNION
SELECT '5BA4', '李五', 'decline' UNION
SELECT '4A87', '王四', 'deleted'



SELECT Uid,Uname,result
FROM tba
ORDER BY CASE result WHEN 'created' THEN 1
                     WHEN 'decline' THEN 2
                     WHEN 'Apprved succeed' THEN 3
                     WHEN 'Approving' THEN 4
                     WHEN 'deleted' THEN 5 END

------解决方案--------------------
修改一下失误
with a as (
select 1 id,'created' rs union 
select 2,'decline' union
select 3,'Apprved' union
select 4,'succeed' union
select 5,'Approving' union 
select 6,'deleted')
select tb.* from tb join a on tb.result=a.rs order by id

探讨

SQL code

with a as (
select 1 id,'created' rs union
select 2,'decline' union
select 3,'Apprved' union
select 4,'succeed' union
select 5,'Approving' union
select 6,'deleted')
select * from tb jo……