1

I am trying to pivot this data but I am getting an error of

Msg 102, Level 15, State 1, Line 16
Incorrect syntax near ','.

Highlighting the comma after SUM([Total Count]) but it has to be there, what should I change so my query executes properly?

select *
FROM
(
  select a.regionalLocale As [RL], 
  Count(ID) As [Total Count], 
  CONVERT(VARCHAR(20), dt.week) AS Week
  FROM database14.dataTable a
  INNER JOIN calendarDB.masterCalendar dt
  ON a.SaleDate = dt.FullDate
  WHERE a.SaleDate IS NOT NULL
) src
pivot
(
  SUM([Total Count]), [RL]
  For Week IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13])
) piv
8
  • What's , [RL] after the sum([total..)?
    – Taryn
    Apr 1, 2015 at 20:46
  • The alias for regionalLocale in the query above
    – Big Pimpin
    Apr 1, 2015 at 20:47
  • You can't pivot on multiple columns like that. What do you expect the final result to be? Did you try removing that?
    – Taryn
    Apr 1, 2015 at 20:47
  • Going vertically down left side I want to show a.regionalLocale, horizontally across the top I want to show Week, and the data portion of things I want to show Count(ID)
    – Big Pimpin
    Apr 1, 2015 at 20:50
  • 1
    Change Count(ID) to just be id inside the subquery and then change SUM([Total Count]) to count(id) for the PIVOT. You don't need to aggregate inside your subquery, let the pivot do ti
    – Taryn
    Apr 1, 2015 at 20:55

1 Answer 1

0

You've got a few issues with your query.

One you've got the syntax SUM([Total Count]), [RL] in your PIVOT. You only want to include the column you are aggregating here.

Second, there is no need to use count(id) inside your subquery, let the PIVOT aggregation handle the total. Change your code to:

select [RL], 
  [1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13]
FROM
(
  select a.regionalLocale As [RL], 
    ID, 
    CONVERT(VARCHAR(20), dt.week) AS Week
  FROM database14.dataTable a
  INNER JOIN calendarDB.masterCalendar dt
    ON a.SaleDate = dt.FullDate
  WHERE a.SaleDate IS NOT NULL
) src
pivot
(
  COUNT(ID)
  For Week IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13])
) piv

Your Answer

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

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