I'm currently moving an MS Access db to SQL Server. I have a cross-tab query
I'm needing to convert to a Pivot table
.
The Pivot table
will be in a sproc
that gives parameters for the month
and year
. Those parameters are put into the WHERE
clause of a subquery
.
SQL so far:
SELECT IDNbr, [Name]
FROM (SELECT a1.IDNbr , a2.[CustName] as [Name] , a1.BalDate, a1.Balance
FROM IDTable a1 INNER JOIN CustTable a2 ON (a1.IDNbr = a2.IDNbr)
WHERE MONTH(a1.BalDate) = @month AND YEAR(a1.BalDate) = @year) as d1
PIVOT (
SUM(Balance)
For Balance in ([BalDate]) --Error: see below
) piv;
The error I get in the Pivot
section is:
The column name "BalDate" specified in the PIVOT operator conflicts with the existing column name in the PIVOT argument.
And I'm also getting the error:
The column 'BalDate' was specified multiple times for 'piv'.
Current data:
Customer | BalDate | Balance
----------+-------------+--------
Customer1 | 1/01/2017 | 0.00
Customer1 | 1/02/2017 | 0.00
Customer1 | 1/03/2017 | 0.00
Customer1 | 1/04/2017 | 0.00
.... | .... | ....
Desired data:
| Customer | 01/01/2017 | 01/02/2017 | 01/03/2017 | 01/04/2017 | 01/05/2017 | 01/06/2017 | 01/07/2017 | 01/08/2017 | 01/09/2017 | 01/10/2017 | ....
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| Customer1 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | ....
| Customer2 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | ....
| Customer3 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | ....
Primary Question: How would I go about correcting the errors in my Pivot Table
?
Secondary Question: How would I be able to get the Current data
to Desired data
?
I'm still very much a beginner in SQL and SQL Server so I apologize if the answer is obvious.
Thank you in advance for any help and advice! And I will gladly try to clarify on anything that seems confusing or unclear!
Posts I've referenced, and attempted to apply to my situation:
Column name specified in the pivot operator conflicts
Column was specified multiple times