简体   繁体   中英

Access SQL Pivot Query That Includes Blank Fields

I'm trying to write an Access SQL pivot query that displays values in a single row for all codes in a table for a given ID value, even if the fields are blank. So far, everything that I've tried has returned either multiple rows or, if the data's on one row, any blank fields get left out.

I've tried this as a pivot query, as a self-join, using IIF, as a union query, and anything else I could think of or find online.

Sample Data:
ID    TypeCode  TypeID
248    AT       3013
329    AT       7465
329    PL       7998
329    TJ       6232
477    NX       1403

Desired results on a query of ID 329:
ID      AT      PL      TJ      NX
329     7465    7998    6232    <blank>

What I get: 
ID    AT    PL      TJ
329   7465  7998    6232

or 
ID    AT    PL      TJ
329   7465  
329         7998
329                 6232

Desired results on a query of ID 248:
ID    AT     PL       TJ      NX
248   7465   <blank>  <blank> <blank>

What I get:
ID    AT
248   7465

Sample query:
TRANSFORM Avg(MyTable.[ID]) AS ID
SELECT MyTable.[ID], TypeCode, TypeID
FROM MyTable WHERE MyTable.ID = 329
GROUP BY TypeCode, TypeID
PIVOT MyTable.TypeCode;

I've tried adding IFF statements to the SELECT fields, but no dice.

I'm hoping someone can suggest the right approach I should be using to end up with the desired results shown above. Thanks for any help you can give.

You must group by ID and get the columns with conditional MAX:

SELECT ID,
MAX(IIF(TypeCode = 'AT', TypeID, NULL)) AS AT,
MAX(IIF(TypeCode = 'PL', TypeID, NULL)) AS PL,
MAX(IIF(TypeCode = 'TJ', TypeID, NULL)) AS TJ,
MAX(IIF(TypeCode = 'NX', TypeID, NULL)) AS NX
FROM MyTable
WHERE ID = 329
GROUP BY ID;

Results:

ID    AT        PL      TJ     NX
329   7465      7998    6232    

If you remove the WHERE part, the result is:

ID    AT        PL      TJ      NX
248   3013          
329   7465      7998    6232    
477                             1403

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM