订购sql查询数据

时间:2012-05-07 10:58:31

标签: sql sql-server sql-server-2005

我有一个问题:

select * from
(
select i.id, i.art_id, i.c_izm, i.c_zime_izm, i.ac_izm, i.rc_izm, i.f_nos, convert(nvarchar,dateadd(mi,-30,i.datums),100) as dat
from nol_art_izmaina i
inner join nol_art a on i.art_id=a.id
where datepart(year,print_dat)=2005
order by a.nos --when I add this row, the error shows
union all
select distinct null,null,'','','','', f_nos, min(dat)
from nol_art_izmaina 
where datepart(year,print_dat)=2005
group by f_nos
)tablePlusHeaders
order by dat desc

我需要什么?我需要来自第一个查询的数据按a.nos值排序。我该怎么做?

修改
结果表应如下所示,但仅限于我的数据:

Name   ImpFile/Job         Year
--------------------------------
       Imp01 20.01.2012              This is from set2
John   Clerk               1986    This is from set1
James  Assistant           1990    This is from set1
       Imp02 26.02.2012              This is from set2
Anna   Manager             1982    This is from set1
Sam    Salesman            1985    This is from set1
Dean   Cleaner             1985    This is from set1

1 个答案:

答案 0 :(得分:1)

错误可能是因为没有列nos,而是f_nos。要订购联合,您需要为每个选择添加一个标记,然后按f_nos和那个标记排序:

select * from
(
  select i.id, i.art_id, i.c_izm, i.c_zime_izm, i.ac_izm, i.rc_izm, i.f_nos, 
         convert(nvarchar,dateadd(mi,-30,i.datums),100) as dat,
         0 set_id
    from nol_art_izmaina i
   inner join nol_art a on i.art_id=a.id
   where datepart(year,print_dat)=2005
   union all
  select distinct null,null,'','','','', f_nos, min(dat),
         1 set_id
    from nol_art_izmaina 
   where datepart(year,print_dat)=2005
   group by f_nos
) tablePlusHeaders
order by f_nos, set_id, dat desc