无法通过group by子句组合sql中的行

时间:2015-09-30 10:09:35

标签: sql sql-server

我想在sql server 2005中将三行组合为一行,我尝试使用group by子句,但我无法将这三行合并为一行

下面是代码,我写的是

select * from 
(
select 
   case 
   when  postatus = 'y' and  approverid = '1111' 
   then Convert(varchar(10),  trasdate ,103) 
   end as [col1],
   case
   when  postatus = 'y' and  approverid = '401'
   then Convert(varchar(10),  trasdate ,103)
   end as [col2],
   case
   when  postatus = 'y' and ( approverid = '329' or  approverid = '1495' or  approverid = '1239')
   then Convert(varchar(10),  trasdate ,103)
   end as [col3]
from tblpo_approvalstatus where prnumber = '000002'
) as t
group by
col1,col2,col3

我的结果是

col1      col2       col3
9/6/2015  NULL       NULL
NULL      9/8/2015   NULL
NULL      NULL       9/15/2015

我想将它们作为一行

col1       col2         col3
9/6/2015   9/8/2015     9/15/2015

提前致谢

2 个答案:

答案 0 :(得分:0)

你试过这个吗?

select no, max([po date]), max([pr date]), max([qar date])
from t
group by no;

答案 1 :(得分:0)

您希望聚合数据,因此请使用聚合函数。在您的情况下,每列只有一个值(因为prnumber + postatus + approverid在该表中是唯一的?也许他们构建主键?),您可以使用MIN或MAX或甚至AVG,没有区别。

select 
  convert(varchar(10), max(case when postatus = 'y' and approverid = '1111' then trasdate end) ,103) as col1,
  convert(varchar(10), max(case when postatus = 'y' and approverid = '401' then trasdate end) ,103) as col2,
  convert(varchar(10), max(case when postatus = 'y' and approverid in ('329','1495','1239') then trasdate end) ,103) as col3
from tblpo_approvalstatus 
where prnumber = '000002';
顺便说一下,GROUP BY绝对不合适。使用GROUP BY x, y,您说"请汇总我的数据,以便每个x和y"得到一个结果行,但您不希望每个获得一个结果行 (所以不是GROUP BY)。