2

当我尝试执行下面的查询时,出现错误

关键字“convert”附近的语法不正确

而且我不确定我在哪里犯了错误。qty 字段的数据类型是 nchar,所以我使用转换函数来查找总计。

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

等等...

4

2 回答 2

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

SE-数据

于 2012-07-05T18:02:11.843 回答
0

你试过cast(gty as int)吗?

于 2012-07-05T15:39:42.877 回答