【问题标题】:Move date column across in SQL Partition By Clause在 SQL Partition By Clause 中移动日期列
【发布时间】:2022-01-09 04:53:58
【问题描述】:

我有以下代码:


with cte as (

select projectNum, 

 
  [1] as L1A,
  [2] as L2A,
  [3] as L3A,
  [4] as L4A,   
  [5] as L5A
from (
  select d.projectNum, d.createdDate, d.dateId
  from (
    select dd.rn as dateId, dd.createdDate, dd.projectNum
    from (
      select ProjectNum, format(CreatedDate,'MM/dd/yyy') as 'CreatedDate', row_number() over (partition by projectNum order by createdDate asc) rn
      from DWCorp.SSMaster m 
INNER JOIN DWCorp.SSDetail d ON d.MasterId = m.Id WHERE  ActionId = 7 and projectnum = 'obel00017'
      ) dd
    where rn <= 5
   -- order by 3, 1
    ) d
  ) as src
  pivot (
    max(createdDate)
    for dateId in ([1],[2],[3],[4],[5])
    
  ) as pvt)

  
  
  select *  from cte
  

返回:

当我运行这个查询时,上面的查询基于:

select ProjectNum, format(CreatedDate,'MM/dd/yyy') as 'CreatedDate', LevelId
  from DWCorp.SSMaster m 
INNER JOIN DWCorp.SSDetail d ON d.MasterId = m.Id WHERE  ActionId = 7 and ProjectNum = 'obel00017'
and LevelId  in (1,2,3,4,5)

返回:

我需要将结果放在正确的列中。 L1A 中不应该有值,并且所有内容都应该向右移动一个。不知道为什么会这样。下面是它的外观示例。

【问题讨论】:

    标签: sql sql-server-2012 row-number partition-by


    【解决方案1】:

    pivot 查询正在计算列的 row_number。

    但是你已经得到了那个 LevelId。

    所以替换它。

    select 
      projectNum
    , [1] as L1A
    , [2] as L2A
    , [3] as L3A
    , [4] as L4A
    , [5] as L5A
    from
    (
      select 
        ProjectNum
      , format(CreatedDate,'MM/dd/yyyy') as CreatedDate
      , LevelId
      from DWCorp.SSMaster m 
      join DWCorp.SSDetail d on d.MasterId = m.Id 
      where  ActionId = 7 
      and projectnum = 'obel00017' 
      and LevelId <= 5
    ) as src
    pivot 
    (
      max(createdDate)
      for LevelId in ([1],[2],[3],[4],[5])
    ) as pvt
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-14
      • 1970-01-01
      • 1970-01-01
      • 2021-12-15
      • 2021-10-29
      相关资源
      最近更新 更多