0

I have the following table and want to create a new table with the data pivoted.

[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

And would like to use Access VBA SQL to pivot the data as follows:

[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

I see a lot of examples of how to pivot with just 3 columns e.g.; [Report Date] [Desc] [Value]. Pivoting data in MS Access How can the other attribute columns be carried along?

Dan
  • 1

2 Answers2

1

You can use:

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]

Output:

enter image description here

Gustav
  • 53,498
  • 7
  • 29
  • 55
0

Simply specify the other columns in SELECT and GROUP BY clauses of MS Access's crosstab query which contains an aggregate query nested within:

TRANSFORM MAX([Value])
SELECT [Report Date], [Name], [Location]
FROM myTable
GROUP BY [Report Date], [Name], [Location]
PIVOT [Desc]; 
Parfait
  • 104,375
  • 17
  • 94
  • 125