When I try to execute the query below, I get error
Incorrect syntax near the keyword ‘convert’
and I’m not sure where I made mistake. The data type for qty field is nchar so I used convert function for finding totals.
select column_date, [red] as red, [blue] as blue, [green] as green, [yellow] as yellow
from
(select * from table1) as t1
pivot
(
sum(convert(int,qty))
For color in
([red], [blue], [green], [yellow])
) as SumofQuantityforeachcolor
Here is the table
column_date | color | qty | supplier
1 June 2012 | red | 2 | XY
1 June 2012 | red | 1 | AB
1 June 2012 | blue | 4 | CD
1 June 2012 | blue | 1 | XY
2 June 2012 | yellow| 13 | CD
2 June 2012 | green | 45 | CD
2 June 2012 | blue | 32 | AB
2 June 2012 | red | 37 | XY
2 June 2012 | red | 2 | XY
2 June 2012 | red | 1 | AB
2 June 2012 | blue | 4 | CD
3 June 2012 | red | 1 | AB
3 June 2012 | blue | 4 | CD
3 June 2012 | blue | 1 | XY
3 June 2012 | yellow| 13 | CD
3 June 2012 | green | 45 | CD
3 June 2012 | blue | 32 | AB
and so on…
Don’t use
select *in your sub query. List all columns you need and do the type cast in the field list instead of in thesum()function.The aggregate function in a pivot does not take an expression as an argument. You have to specify a column.
You are probably looking for something like this.
SE-Data