简体   繁体   English

SQL 匹配新列

[英]SQL match to new column

I am using SQL in Microsoft access.我在 Microsoft 访问中使用 SQL。 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.我想要一个查询,该查询返回一行,其中每个唯一的条形码和前 5 个值中的每个值的列。 Right now, I have a query returning the last value or the first value with min or max.现在,我有一个查询返回最后一个值或第一个值,最小值或最大值。 How can I get the 2nd, 3rd, 4th, 5th value into separate columns?如何将第 2、第 3、第 4、第 5 个值放入单独的列中?

Table:桌子:

桌子

Current query:当前查询:

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

Current output:当前 output:

电流输出

Goal output:目标 output:

目标输出

This is rather tricky.这是相当棘手的。 I think you are stuck with conditional aggregation and a correlated subquery in MS Access.我认为您在 MS Access 中遇到了条件聚合和相关子查询。 Note that the following assumes that the values are unique:请注意,以下假设值是唯一的:

select barcode,
       max(iif(seqnum = 1, value, null)),
       max(iif(seqnum = 2, value, null)),
       max(iif(seqnum = 3, value, null)),
       max(iif(seqnum = 4, value, null)),
       max(iif(seqnum = 5, value, null))
from (select t.*,
             (select count(*)
              from t as t2
              where t2.barcode = t.barcode and t2.value <= t.value
             ) as seqnum
      from t
     ) t
group by barcode;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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