对计算值进行SQL排序

时间:2014-06-17 21:25:54

标签: mysql sql

我需要帮助对使用SQL查询创建的报表进行排序。

    select (CASE WHEN I4220 = '1' OR I4225='VDRRTN' then 'High' else 'Normal' END) 'Priority', i4224 'Arrived', GETDATE() - Inventory.I4224 'Days in Lab Status',i4201 'Asset', i4202 'Mfg', i4203 'Model', i4204 'Description', i4218 'Loc', i4225 'Status', 
I4214 'Lab', I4205 'LNO', I4299 'State', (CASE WHEN I4223 like '%IN%' THEN 'IN' else 'DIRECT' END) 'Overhead', I4251 'Need By Date'
from Inventory
where (i4299 in ('A','I'))and
    (i4225 in ('DEPVDRTN', 'FLOORCAL', 'LAB', 'VDRRTN'))  AND I4240 != 'SV_F35'
order by I4220 DESC, i4224 ASC;

我想按'优先级'对查询结果进行排序,但根据case语句将优先级设置为“High”。

select (CASE WHEN I4220 = '1' OR I4225='VDRRTN' then 'High' else 'Normal' END)

我希望所有标记为“高”的项目都位于报告的顶部,然后我希望按日期按升序排序。

有什么想法吗?

谢谢, 贾斯汀。

2 个答案:

答案 0 :(得分:1)

您可以按顺序重复计算:

select (CASE WHEN I4220 = '1' OR I4225='VDRRTN' then 'High' else 'Normal' END) 'Priority', i4224 'Arrived', GETDATE() - Inventory.I4224 'Days in Lab Status',i4201 'Asset', i4202 'Mfg', i4203 'Model', i4204 'Description', i4218 'Loc', i4225 'Status', 
I4214 'Lab', I4205 'LNO', I4299 'State', (CASE WHEN I4223 like '%IN%' THEN 'IN' else 'DIRECT' END) 'Overhead', I4251 'Need By Date'
from Inventory
where (i4299 in ('A','I'))and
    (i4225 in ('DEPVDRTN', 'FLOORCAL', 'LAB', 'VDRRTN'))  AND I4240 != 'SV_F35'
  order by (CASE WHEN I4220 = '1' OR I4225='VDRRTN' then 'High' else 'Normal' END) ASC;

或者您可以将查询包装起来计算一次(至少在TSQL中):

Select * from (
select (CASE WHEN I4220 = '1' OR I4225='VDRRTN' then 'High' else 'Normal' END) 'Priority', i4224 'Arrived', GETDATE() - Inventory.I4224 'Days in Lab Status',i4201 'Asset', i4202 'Mfg', i4203 'Model', i4204 'Description', i4218 'Loc', i4225 'Status', 
    I4214 'Lab', I4205 'LNO', I4299 'State', (CASE WHEN I4223 like '%IN%' THEN 'IN' else 'DIRECT' END) 'Overhead', I4251 'Need By Date'
    from Inventory
    where (i4299 in ('A','I'))and
        (i4225 in ('DEPVDRTN', 'FLOORCAL', 'LAB', 'VDRRTN'))  AND I4240 != 'SV_F35'
) x
order by 'Priority' ASC;

答案 1 :(得分:0)

您可以在order by子句中引用列别名:

select (CASE WHEN I4220 = '1' OR I4225='VDRRTN' then 'High' else 'Normal' END) as Priority,
       i4224 as Arrived, GETDATE() - Inventory.I4224 `Days in Lab Status`,
       i4201 as Asset, i4202 as Mfg, i4203 as Model, i4204 as Description, i4218 as Loc,
       i4225 as Status, I4214 as Lab, I4205 as LNO, I4299 as State,
       (CASE WHEN I4223 like '%IN%' THEN 'IN' else 'DIRECT' END) as Overhead,
       I4251 as `Need By Date`
from Inventory
where (i4299 in ('A','I'))and
      (i4225 in ('DEPVDRTN', 'FLOORCAL', 'LAB', 'VDRRTN'))  AND I4240 <> 'SV_F35'
order by Priority, i4224 ASC;

更重要的是,您不应该使用单引号作为标识符。在MySQL中,如果需要转义名称,则可以使用反引号。对于你的大部分名字,这是不必要的。只对字符串和日期常量使用单引号可以防止将来出现错误。

同样,对列别名使用as是一个好主意。这样,一个流浪逗号不会在你的select条款中引起问题。