访问Pivot SQL由多列分组

时间:2018-01-20 02:25:36

标签: sql ms-access

我有下表,想要创建一个包含数据透视的新表。

[report date] [Name] [Location] [Desc] [Value]
1/1/2017 Bob Spain Sales 10
1/1/2017 Bob Spain Costs 5
2/1/2017 Bob Spain Sales 20
2/1/2017 Bob Spain Costs 8
1/1/2017 Tom Spain Sales 9
1/1/2017 Tom Spain Costs 4
2/1/2017 Tom Spain Sales 19
2/1/2017 Tom Spain Costs 7

并且希望使用Access VBA SQL来按如下方式转动数据:

[Report Date] [Name] [Location] [Sales] [Costs]
1/1/2017 Bob Spain 10 5
2/1/2017 Bob Spain 20 8
1/1/2017 Tom Spain  9 4
2/1/2017 Tom Spain 19 7

我看到很多如何用3列旋转的例子,例如; [Report Date] [Desc] [Value]Pivoting data in MS Access如何携带其他属性列?

2 个答案:

答案 0 :(得分:1)

您可以使用:

Select 
    [report date], 
    [Name],
    [Location],
    Sum(IIf([Desc] = 'Sales', [Value], 0)) As Sales,
    Sum(IIf([Desc] = 'Costs', [Value], 0)) As Costs
From
    YourTable
Group By
    [Name],
    [Location],
    [report date]

答案 1 :(得分:0)

只需指定MS Access的交叉表查询的tlSELECT子句中的其他列,其中包含嵌套在其中的聚合查询:

GROUP BY