Note that there are some explanatory texts on larger screens.

plurals
  1. PODynamic pivot - how to obtain column titles parametrically?
    primarykey
    data
    text
    <p>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.</p> <p>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.</p> <p>Rather I want the column headings to be parametrically generated, so that if I input:</p> <pre> -------------------------------------- Query - Selection Criteria -------------------------------------- Posting Date greater or equal 01.09.10 Posting Date smaller or equal 31.08.11 [OK] [Cancel] </pre> <p>the Query will generate the following columns:</p> <p>Sep-10, Oct-10, Nov-10, ..... Aug-11</p> <p>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 <code>Incorrect Syntax near 20100901</code>.</p> <p>Could anybody help me locate my error?</p> <p>Note: In SAP B1, '[%1]' is an input variable</p> <p>Here's my query:</p> <pre><code>/*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] &gt;= '[%1]' AND T0.[Refdate] &lt;= '[%2]' ) S PIVOT ( Sum(Amount) FOR [Month] IN ('+@listCol+') ) AS pvt ' -------------------------------------------- /*Section 4*/ EXECUTE (@query) </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload