OK, I think it is time for a new thread as my last one was a bit off. I am trying to create a report I have gone to SQL 2005 and this is my first attempt with CTEs and Pivot Tables. I have this
which is still telling me there is an error in line 21 (FOR init_date...) near'('. I know this is not correct and have been unable to find the correct solution to this problem. Without the Pivot, the query with the CTE gives me the first (up to) three separate purchase dates for each customer with the number of items purchased each time. My goal in adding the Pivot was to make each row in the recordset contain everything for each customer, so rather than having three lines, one for each purchase date (dtAssigned), I could have one line with all (up to) three purchase dates included. It looks to me like this should be a fine situation to use Pivot as NiceArms suggested, but it seems to be choking where I narrow the datetime field down to just the date.
Any help?
Thanks,
wb
Code:
WITH Purchases AS
(
SELECT
iownerid, DATEADD(dd, DATEDIFF(dd,0,dtassigned), 0) as init_date, count(DATEADD(dd, DATEDIFF(dd,0,dtassigned), 0)) as num_purch,
RANK() OVER (PARTITION BY iownerid ORDER BY DATEADD(dd, DATEDIFF(dd,0,dtassigned), 0) ASC) AS 'pdate'
FROM
tmasterserialnumbers
GROUP BY iOwnerID, DATEADD(dd, DATEDIFF(dd,0,dtassigned), 0)
)
select * from (
SELECT
iownerid, init_date, num_purch
FROM
Purchases
WHERE
pdate <= 3
GROUP BY iOwnerId, init_date, num_purch ) Purchases
PIVOT
(
SUM(iownerid)
FOR init_date IN (DATEADD(dd, DATEDIFF(dd,0,dtassigned), 0))
) AS PivotTable
which is still telling me there is an error in line 21 (FOR init_date...) near'('. I know this is not correct and have been unable to find the correct solution to this problem. Without the Pivot, the query with the CTE gives me the first (up to) three separate purchase dates for each customer with the number of items purchased each time. My goal in adding the Pivot was to make each row in the recordset contain everything for each customer, so rather than having three lines, one for each purchase date (dtAssigned), I could have one line with all (up to) three purchase dates included. It looks to me like this should be a fine situation to use Pivot as NiceArms suggested, but it seems to be choking where I narrow the datetime field down to just the date.
Any help?
Thanks,
wb