0

I wish to write a Query for SAP B1 (t-sql) that will list all Income and Expenses Items by total and month by month.

I have successfully written a Query using PIVOT, but I do not want the column headings to be hardcoded like: Jan-11, Feb-11, Mar-11 ... Dec-11.

Rather I want the column headings to be parametrically generated, so that if I input:

--------------------------------------
Query - Selection Criteria
--------------------------------------

Posting Date      greater or equal        01.09.10

Posting Date      smaller or equal        31.08.11

[OK]   [Cancel]

the Query will generate the following columns:

Sep-10, Oct-10, Nov-10, ..... Aug-11

I guess DYNAMIC PIVOT can do the trick. So, I modified one SQL obtained from another forum to suit my purpose, but it does not work. The error message I get is Incorrect Syntax near 20100901.

Could anybody help me locate my error?

Note: In SAP B1, '[%1]' is an input variable

Here's my query:

/*Section 1*/

DECLARE @listCol VARCHAR(2000)
DECLARE @query VARCHAR(4000)

-------------------------------------
/*Section 2*/

SELECT @listCol = 
STUFF(
   ( SELECT DISTINCT '],[' + CONVERT(VARCHAR, MONTH(T0.RefDate), 102)
       FROM JDT1 
        FOR XML PATH(''))
     , 1, 2, '') + ']' 

------------------------------------
/*Section 3*/

SET @query = '
SELECT * FROM 
(
   SELECT 
        T0.Account,
        T1.GroupMask,
        T1.AcctName,
        MONTH(T0.RefDate) as [Month],   
        (T0.Debit - T0.Credit) as [Amount]
    FROM dbo.JDT1 T0
   JOIN dbo.OACT T1 ON T0.Account = T1.AcctCode 
   WHERE
      T1.GroupMask IN (4,5,6,7) AND
      T0.[Refdate] >= '[%1]' AND
      T0.[Refdate] <= '[%2]'
 ) S
PIVOT 
(
    Sum(Amount)
    FOR [Month] IN ('+@listCol+')
) AS pvt
'

--------------------------------------------
/*Section 4*/

EXECUTE (@query)

1 Answer 1

0

I don't know SAP, but a couple of things spring to mind:

  • It looks like you want @listCol to contain a collection of numbers within square brackets, for example [07],[08],[09].... However, your code appears not to put a [ at the start of this string.

  • Try replacing the lines

    T0.[Refdate] >= '[%1]' AND
    T0.[Refdate] <= '[%2]'
    

    with

    T0.[Refdate] >= ''[%1]'' AND
    T0.[Refdate] <= ''[%2]''
    

(I also added a space before the AND in the first of these two lines while I was editing your question.)

1
  • Hi Luke, Thanks for your answer. Unfortunately it does not solve my problem. I realize that the solutionn is going to be very difficult. Fortunately, I found this helpful article: simple-talk.com/community/blogs/andras/archive/2007/09/14/… I must now work hard to adapt these ideas to my problem. Best Regards Leon Lai
    – Leon Lai
    Oct 19, 2011 at 5:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.