Skip to content
Advertisement

SQL query put nth match in new column

I am using SQL in Microsoft access. The table may contain more than one value for a bar code. I want to a query that returns one row with each unique bar code and columns for each of the first 5 values. Right now, I have a query returning the last value or the first value with min or max. How can I show the second result in the next column? or the nth result in that column? This is in Access but any other SQL help would be appreciated.

Current table:

current table

Current query:

SELECT table.barcode, MIN(table.value)
FROM table
GROUP BY table.barcode

Current output:

current output

Goal query output:

gola query output

Advertisement

Answer

You can use aggregation:

SELECT table.barcode,
       MIN(table.value),
       IIF(MIN(table.value) = MAX(table.value), MAX(table.VALUE), NULL)
FROM table
GROUP BY table.barcode
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement