-1

Hi guys I'm trying to use unpivot in SQL on MS Access and I found the following code online:

SELECT CustomerID, Phone
FROM
(
  SELECT CustomerID, Phone1, Phone2, Phone3 
  FROM dbo.CustomerPhones
) AS cp
UNPIVOT 
(
  Phone FOR Phones IN (Phone1, Phone2, Phone3)
) AS up;

from this webpage: https://www.mssqltips.com/sqlservertip/3000/use-sql-servers-unpivot-operator-to-help-normalize-output/

However when I tried the exact same code on Access, it keeps saying the FROM clause has an error.

I wonder if this is because the syntax for access is somehow different from that in SQL server? I would really appreciate it if anyone could tell me how to make this code run.

Jeff
  • 12,555
  • 5
  • 33
  • 60
Joy
  • 5
  • 3
  • Access doesn't have a built-in `UNPIVOT` functionality, q.v. [here](http://stackoverflow.com/questions/7255423/how-to-simulate-unpivot-in-access-2010). If you include sample data someone might be able to give you a workaround. – Tim Biegeleisen Oct 06 '16 at 01:43

2 Answers2

3

Just use union all:

SELECT CustomerID, Phone1 as Phone
FROM dbo.CustomerPhones
UNION ALL
SELECT CustomerID, Phone2 as Phone
FROM dbo.CustomerPhones
UNION ALL
SELECT CustomerID, Phone3 as Phone
FROM dbo.CustomerPhones;

If you want to incur the overhead of removing duplicates, then use UNION.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

Bear in mind, if you are really reading from the actual database, you can make use of all RDMBS-specific functionality (in this case MS SQL Server) by using a pass-thru instead of an Access-specific query. The only thing you lose is the designer tools. What I'm saying is you can literally paste your query as-is into Access and use it like any other Access query.

If the table is already in Access (divorced from the linked data source) or isn't supported via pass-thru, this might work. It's pretty brute-force, but if you create a table (call it "Sequence" in this example) with a single field called ID:

ID
1
2
3

Then you can do a cross (Cartesian) join against your Phones table:

select
  p.[CustomerId],
  s.[ID],
  switch (
    s.[ID] = 1, p.[Phone1],
    s.[ID] = 2, p.[Phone2],
    s.[ID] = 3, p.[Phone3]
  ) as Phone
from
  [CustomerPhones] as p,
  [Sequence] as s

The sequence table may have another workaround... Postgresql has a function called generate_series that would be perfect, but I don't know the equivalent in Access.

Hambone
  • 15,600
  • 8
  • 46
  • 69