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-2026-white.png



April 27 – 30 | Gaylord Texan | Grapevine, Texas

Registration is open

Walk in ready to learn. Walk out ready to deliver. This is the data and AI conference you can't afford to miss.
Register now and lock in 2025 pricing—just $495!

Register now

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
  • 668 views
  • 0 likes
  • 2 in conversation