在 SQL Partition By Clause 中移动日期列
Move date column across in SQL Partition By Clause
我有以下代码:
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
哪个returns:
当我运行这个查询时,上面的查询是基于:
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)
它returns:
我需要将结果放在正确的列中。 L1A 不应该有值,一切都应该向右移动一个。不知道为什么会这样。下面的示例。
数据透视查询正在计算列的 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
我有以下代码:
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
哪个returns:
当我运行这个查询时,上面的查询是基于:
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)
它returns:
我需要将结果放在正确的列中。 L1A 不应该有值,一切都应该向右移动一个。不知道为什么会这样。下面的示例。
数据透视查询正在计算列的 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