【问题标题】:SQL to get the first occurence of a value in each column within grouped elementsSQL 获取分组元素内每列中第一次出现的值
【发布时间】:2014-08-21 07:33:04
【问题描述】:

我正在使用 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

所以我基本上需要对“行”列进行分组,包括组内每一列的第一个非空值。

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

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

【问题讨论】:

  • 虽然您的示例数据没有显示出来,但是给定的行和列可以有多个值吗?给定的行可以有多个代码吗?
  • 不,对于每个“行”值,每列中只会出现一个非空值。每个“行”值也不会有多个“代码”值。

标签: sql sql-server tsql reporting-services


【解决方案1】:

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

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

【讨论】:

  • 这不会得到想要的结果,您需要删除 Code 列上的聚合并将其包含在 GROUP BY 中:GROUP BY Line, Code
  • @dimt 我明白你的意思。你可能是对的 - 我会做出改变
【解决方案2】:

这对我有用:

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

【讨论】:

    猜你喜欢
    • 2018-03-19
    • 1970-01-01
    • 2021-09-14
    • 1970-01-01
    • 1970-01-01
    • 2019-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多