我在MS Access中有以下声明:
TRANSFORM Sum([TABLE1].CountOftext) AS SumOfCountOftext
SELECT
[TABLE1].[ID],
[TABLE1].FOS,
[TABLE1].VTCD,
Sum([TABLE1].CountOftext) AS [Total Of CountOftext]
FROM [TABLE1]
GROUP BY [TABLE1].[ID], [TABLE1].FOS, [TABLE1].VTCD
PIVOT [TABLE1].text_status;
我的表格是TABLE1
,看起来像是:
+--------------+-----+--------+------+-------------+-------------+
| ID | FOS | MD | VTCD | TEXT_STATUS | COUNTOFTEXT |
+--------------+-----+--------+------+-------------+-------------+
| 822234361802 | PS4 | 10X10F | XTAP | APP | 1 |
| 822234361802 | PS4 | 10X10F | XTBP | APP | 1 |
| 822234361802 | PS4 | 10X10F | XTFP | APP | 1 |
| 822234361802 | PS4 | 10X10F | XTPD | APP | 1 |
| 822234361802 | PS4 | 10X10F | XTPL | APP | 1 |
+--------------+-----+--------+------+-------------+-------------+
我已经浏览了一些帖子并试图转换但我仍然收到错误,下面是T-SQL中的转换后的查询
SELECT *
FROM
(
SELECT
Sum([TABLE1].CountOftext) AS [Total Of CountOftext] ,
[TABLE1].[ID],
[TABLE1].FOS,
[TABLE1].VTCD
FROM [TABLE1]
) T
PIVOT ( T.[Total Of CountOftext]
FOR T.[text_status] IN (APP, CRE, ORD, REQ, TBA, TBT, WRK )
) P
我得到的错误是:
Msg 156,Level 15,State 1,Line 13关键字'FOR'附近的语法不正确。
有人可以帮助我做错了吗。
需要最终结果。
ID FOS VTCD Total Of CountOftext APP
822234361802 PS4 XTAP 1 1
822234361802 PS4 XTBP 1 1
822234361802 PS4 XTFP 1 1
822234361802 PS4 XTPD 1 1
822234361802 PS4 XTPL 1 1
答案 0 :(得分:2)
您的语法很接近,但内部查询中不需要SUM
,您应该可以使用:
SELECT *
FROM
(
SELECT
[TABLE1].CountOftext ,
[TABLE1].[ID],
[TABLE1].FOS,
[TABLE1].VTCD,
[TABLE1].text_status
FROM [TABLE1]
) T
PIVOT
(
sum(T.CountOftext)
FOR T.[text_status] IN (APP, CRE, ORD, REQ, TBA, TBT, WRK )
) P
聚合函数位于查询的PIVOT部分,而不是在子查询中。