计算SSRS / SQL查询中的第一行数据

时间:2012-09-29 11:08:42

标签: asp.net tsql reporting-services

在我的SSRS报告中,有一个显示以下数据的矩阵......矩阵中的每一个数据都是动态的。

Departure    Arravial     Bus name        Tour
01:51        02:01        07 ABY 04
02:02        02:12        07 AB 978
02:21        02:31        07 ABY 04
02:32        02:42        07 AB 978
03:01        03:11        07 ABY 04
03:02        03:12        07 AB 978
03:31        03:41        07 ABY 04
03:42        03:52        07 AB 978
04:01        04:11        07 ABY 04

我想要做的是计算第一行总线名称并将其放在旁边。这可以用表达式实现吗?或者我如何在SQL中提出这样的查询?我该如何解决这个难题?

Departure    Arravial     Bus name        Tour
01:51        02:01        07 ABY 04       1
02:02        02:12        07 AB 978       
02:21        02:31        07 ABY 04       2
02:32        02:42        07 AB 978       
03:01        03:11        07 ABY 04       3
03:02        03:12        07 AB 978       
03:31        03:41        07 ABY 04       4
03:42        03:52        07 AB 978       
04:01        04:11        07 ABY 04       5

顺便说一下,这是我的查询,

SELECT HCPD.DepartureTime, HCPD.ArrivalTime, V.BusName
FROM HAT_CALISMA_PLANI HCP WITH(NOLOCK)
INNER JOIN HAT_CALISMA_PLANI_DETAY HCPD WITH(NOLOCK) ON HCPD.HatCalismaPlaniKey = HCP.HatCalismaPlaniKey
INNER JOIN VALIDATOR V WITH(NOLOCK) ON V.ValidatorKey = HCPD.ValidatorKey
WHERE HCPD.DepartureTime = @Time AND HCP.HatKey = @HatKey
ORDER BY HCPD.DepartureTime

编辑:总线名称是动态的。

1 个答案:

答案 0 :(得分:2)

您可以通过在查询中应用row_number()来完成此操作:

select DepartureTime, ArrivalTime, BusName,
  case when BusName ='07 ABY 04' 
        then cast(rn as varchar(10))
        else '' end Tour
from
(
  SELECT HCPD.DepartureTime, HCPD.ArrivalTime, V.BusName,
    row_number() over(partition by busname order by departure) rn
  FROM HAT_CALISMA_PLANI HCP WITH(NOLOCK)
  INNER JOIN HAT_CALISMA_PLANI_DETAY HCPD WITH(NOLOCK) 
    ON HCPD.HatCalismaPlaniKey = HCP.HatCalismaPlaniKey
  INNER JOIN VALIDATOR V WITH(NOLOCK) 
    ON V.ValidatorKey = HCPD.ValidatorKey
  WHERE HCPD.DepartureTime = @Time 
    AND HCP.HatKey = @HatKey
) x
order by DepartureTime;

以下是一个示例查询:

select departure, arrival, busname,
  case when busname ='07 ABY 04' 
        then cast(rn as varchar(10))
        else '' end Tour
from
(
  select departure, arrival, busname,
    row_number() over(partition by busname order by departure) rn
  from yourtable
) x
order by departure;

请参阅SQL Fiddle with Demo