当我尝试执行下面的查询时,我收到错误
关键字'convert'
附近的语法不正确
而且我不确定我犯了什么错误。 qty字段的数据类型是nchar,所以我使用convert函数来查找总数。
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
这是表格
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
依旧......
答案 0 :(得分:3)
请勿在子查询中使用select *
。列出所需的所有列,并在字段列表中而不是sum()
函数中执行类型转换。
数据透视表中的聚合函数不会将表达式作为参数。您必须指定一列。
<pivot_clause> ::=
( aggregate_function ( value_column [ [ , ]...n ])
FOR pivot_column
IN ( <column_list> )
)
你可能正在寻找类似的东西。
select column_date, [red] as red, [blue] as blue, [green] as green, [yellow] as yellow
from (
select column_date,
color,
cast(qty as int) as qty
from table1
) as T
pivot
(
sum(qty)
for color in ([red], [blue], [green], [yellow])
) as SumofQuantityforeachcolor
答案 1 :(得分:0)
您是否尝试使用cast(gty as int)
?