SQL用于获取分组元素中每列中第一个值的出现

时间:2014-08-21 07:33:05

标签: sql sql-server tsql reporting-services

我正在使用SQL Server和Reporting Services构建报表。我有一个类似于以下所有列类型为VARCHAR的数据集:

Line    Code    Col1    Col2    Col3    Col4
============================================
1       xxx     1.1                     
1       xxx             2.3             
1       xxx                     8.7     
1       xxx                             3.4
2       yyy     5.3                     
2       yyy             !err            
2       yyy                     6.5     
2       yyy                             9.1

我的报告应该有这样的输出:

Line    Code    Col1    Col2    Col3    Col4
============================================
1       xxx     1.1     2.3     8.7     3.4
2       yyy     5.3     !err    6.5     9.1

所以我基本上需要在“Line”列上执行分组,包括组中每列的第一个非空值。

如果列是数字类型,我可以使用SUM来获得所需的结果,但由于我正在处理VARCHAR,我无法使用SUM。我也无法将VARCHAR转换为数值,因为如果我的值是非数字值(例如我的例子中的“!err”建议),那么它将不会显示。 / p>

我可以使用什么查询来获得所需的结果?

2 个答案:

答案 0 :(得分:0)

由于给定的行/代码只能有一个col-n值,这对您有用:

select
    line,
    code,
    max(col1) col1,
    max(col2) col2,
    max(col3) col3,
    max(col4) col4
from mytable
group by line, code

答案 1 :(得分:0)

这对我有用:

declare @t table (line int, code varchar(4), c1 varchar(5), c2 varchar(5), c3 varchar(5), c4 varchar(5))

insert into @t (line, code, c1, c2, c3, c4) values (1, 'xxx', '1.5', '', '', '')
insert into @t (line, code, c1, c2, c3, c4) values  (1, 'xxx', '', 'err!', '', '')
insert into @t (line, code, c1, c2, c3, c4) values  (1, 'xxx', '', '', '2.3', '')
insert into @t (line, code, c1, c2, c3, c4) values  (1, 'xxx', '', '', '', '3.5')

insert into @t (line, code, c1, c2, c3, c4) values (2, 'yyy', '1.2', '', '', '')
insert into @t (line, code, c1, c2, c3, c4) values  (2, 'yyy', '', '0.8', '', '')
insert into @t (line, code, c1, c2, c3, c4) values  (2, 'yyy', '', '', 'err!', '')
insert into @t (line, code, c1, c2, c3, c4) values  (2, 'yyy', '', '', '', '4.6')

/* IF only one value in each column for a given code */
SELECT M1.Line, M1.Code 
, (SELECT c1 as cc FROM @t WHERE code = M1.code AND c1 <> '') as c1
, (SELECT c2 as cc FROM @t WHERE code = M1.code AND c2 <> '') as c2
, (SELECT c3 as cc FROM @t WHERE code = M1.code AND c3 <> '') as c3
, (SELECT c4 as cc FROM @t WHERE code = M1.code AND c4 <> '') as c4
FROM @t M1
GROUP BY M1.Line, M1.Code