Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Move date column across in SQL Partition By Clause

I have the following code:


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
  

Which returns:

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

When I run this query, which the above query is based on:

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)

It returns:

enter image description here

I need the result to be in the correct columns. L1A should not have a value in it, and everything should shift one to the right. Not sure why this is happening. Example of how it should look below.

enter image description here

>Solution :

The pivot query is calculating a row_number for the column.

But you already got that LevelId.

So replace it.

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading