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.
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.
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.
来源:https://stackoverflow.com/questions/39886153/unpivot-in-access-sql