2

在我们的数据库中,我们有:(x 表示不关心)

GID   UID    COST
================================
A   1    100
A   1    x
A   2    200
A   2    x
B   3    330
B   3    x

客户报告需要如下所示:

   UID    COST
================================
[Group - A]
   1    100
   1    
   2    200
   2    
   ---Subtotal: 300
[Group - B]
   3    330
   3    x
   ---Subtotal: 330
                        ======Total:    630

我在 SSRS 报告中有 2 个组,一个是 GID 组,一个是 UID 组,我尝试了很多方法来总结一组 GID 中 UID 的所有第一个 COST。但没有成功。

如果在水晶报表中这样做,我们可以使用“组更改公式”来实现它。但是在 SSRS 中,我没有找到正确的方法。

请帮助!

4

1 回答 1

0

您可能必须返回 SQL 并创建要求和的列。

使用您的示例:

select 
    GID,
    UID,
    Cost,
    case when row_number()  over(partition by GID,UID ORDER BY GID,UID,Cost) = 1 then Cost else 0 end as firstCostGroup
from
(
    select 'a' as GID, 1 as UID, 100 as Cost
    union
    select 'a', 1, 101
    union
    select 'a', 2, 200
    union
    select 'a', 2, 201
    union
    select 'b', 3, 300
    union
    select 'b', 3, 301 
) as rawdata

row_number 函数需要 SQL 2005 或更高版本。

SQL 2000 的解决方法类似于

drop table #RawData
go
drop table #RawDataFirstRows
GO
create table #RawData
(
id int identity(1,1),
GID varchar(10),
UID int,
Cost int
)

insert into #RawData
    select 'a' as GID, 1 as UID, 100 as Cost 
    union 
    select 'a', 1, 101 
    union 
    select 'a', 2, 200 
    union 
    select 'a', 2, 201 
    union 
    select 'b', 3, 300 
    union 
    select 'b', 3, 301  

create table #RawDataFirstRows
(
id int
)

insert into #RawDataFirstRows
select
rd.id
from #RawData rd
where
rd.id = (select top 1 id from #RawData rw where rd.uid = rw.uid and rd.gid = rw.gid order by rw.gid,rw.uid)


select
rd.GID, rd.UID, rd.Cost, case when rw.id is null then 0 else 1 end as firstCostGroup
from
#RawData rd
left join
#RawDataFirstRows rw on rd.id = rw.id

请注意,where 子句中的嵌套查询非常低效,因为它必须为 #Rawdata 表中的每一行调用该查询。完成工作,但代价是什么?

如果它不会导致数据生产级别的性能问题,那么您可能会没事。

于 2010-11-30T00:05:31.653 回答