2

如何将最右侧的“最后一步”列添加到 SSRS 的报告中?本质上,我需要包含该行中最近日期的列的名称。实际数据将有几千行,每行有大约 15 个日期。

Name      Step X      Step W      Step A      Step B      Step Y     Last Step
-------------------------------------------------------------------------------
John      1/21/2013   1/24/2013   1/3/2013    1/27/2013   1/7/2013   Step B
Sally     1/22/2013   1/24/2013   1/12/2013   1/1/2013    1/5/2013   Step W

SQL Fiddle简单的示例数据。

4

3 回答 3

1

这是一种不使用动态 sql 的方法(因为这是用于报告服务):

SELECT T.*, C.ColName
FROM yourtable T
OUTER APPLY (SELECT TOP 1 *
             FROM (SELECT 'Step X', [Step X]
                   UNION ALL
                   SELECT 'Step W', [Step W]
                   UNION ALL
                   SELECT 'Step A', [Step A]
                   UNION ALL
                   SELECT 'Step B', [Step B]
                   UNION ALL
                   SELECT 'Step Y', [Step Y]) X(ColName,ColValue)
             ORDER BY ColValue DESC) C

小提琴

于 2013-02-18T19:51:21.207 回答
1

这是通过修改第一个问题的查询的另一种方法。这只是将结果添加name到结果中,因此您可以获得max(date)每个名称的:

;with cte as
(
  select name, col, value
  from yourtable
  unpivot
  (
    value
    for col in ([Step X], [Step W], [Step A], [Step B], [Step Y])
  ) unpiv
) 
select t.name, 
  [Step X], 
  [Step W], 
  [Step A], 
  [Step B], 
  [Step Y],
  d.col LastStep
from yourtable t
cross apply
(
  select c1.col
  from cte c1
  inner join
  (
    select name, max(value) MaxDate
    from cte
    group by name
  ) c2
    on c1.value = c2.maxdate
    and c1.name = c2.name
  where t.name = c1.name
) d

请参阅带有演示的 SQL Fiddle

于 2013-02-19T01:40:26.180 回答
0

为了后代的缘故,这里是 bluefeet 对类似问题的回答的修改版本,以及fiddle

WITH cte AS (
    SELECT *, Rank() OVER (PARTITION BY Name ORDER BY value DESC) AS Rank
    FROM (
      SELECT *
      from yourtable
      unpivot
      (
        value
        for col in ([Step X], [Step W], [Step A], [Step B], [Step Y])
      ) unpiv
    ) X
)
SELECT  yt.[Step X]
      , yt.[Step W]
      , yt.[Step A]
      , yt.[Step B]
      , yt.[Step Y]
      , c1.col
FROM yourtable yt
JOIN cte c1
ON   yt.Name = c1.Name
AND  c1.Rank = 1
于 2013-02-18T21:37:12.573 回答