BookmarkSubscribeRSS Feed
VALLY
Fluorite | Level 6

Convert SQL Code to SAS

please assist in converting the below code into SAS .

 

SELECT A.[KEY]

      ,A.[VOLUME]

      ,A.[DATE]

      ,A.[FLAG]

         --,[PREV_MONTH] = DATEADD(MONTH,-1,A.[DATE])

         ,[DIFFERENCE] = CASE

                                         WHEN CAST(A.[VOLUME] AS FLOAT) - CAST(B.[VOLUME] AS FLOAT) IS NULL THEN 0

                                         ELSE CAST(A.[VOLUME] AS FLOAT) - CAST(B.[VOLUME] AS FLOAT)

                                         END

         ,[SUM_] = CAST(A.[VOLUME] AS FLOAT) + CAST(B.[VOLUME] AS FLOAT)

  FROM [ATM Index].[dbo].[CIB_FINALE_2]                A

  LEFT JOIN [ATM Index].[dbo].[CIB_FINALE_2]    B

  ON          B.[KEY]  = A.[KEY]

              AND B.[FLAG] = A.[FLAG]

              AND MONTH(B.[DATE]) = MONTH(DATEADD(MONTH,-1,A.[DATE]))

  

  ORDER BY 1,3,4    

1 REPLY 1
Kurt_Bremser
Super User

Rough try:

proc sql;
select
  a.key,
  a.date,
  a.flag,
  intnx('month',a.date,-1) as prev_month,
  case
    when (a.volume - b.volume) is missing then 0
    else (a.volume - b.volume)
  end as difference,
  sum(a.volume,b.volume) as sum_
from cib_finale a left join cib_finale b
on
  a.key = b.key and
  a.flag = b.flag and
  month(intnx('month',a.date,-1)) = month(b.date)
order by 1,3,4
;
quit;

Mind that this will cause problems if data from more than one year is present in the source table. Could it be that the MONTH function in the database returns a combination of year and month?

SAS Innovate 2025: Call for Content

Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!

Submit your idea!

Mastering the WHERE Clause in PROC SQL

SAS' Charu Shankar shares her PROC SQL expertise by showing you how to master the WHERE clause using real winter weather data.

Find more tutorials on the SAS Users YouTube channel.

Discussion stats
  • 1 reply
  • 408 views
  • 0 likes
  • 2 in conversation