【问题标题】:How can I Select 1st, 2nd and 3rd values in different columns - Ms Access如何在不同的列中选择第一个、第二个和第三个值 - Ms Access
【发布时间】:2019-11-17 21:07:27
【问题描述】:

我在表格中有这些数据:

 ID     ItemID    ItemSupplier
 1        1           E
 2        2           E
 3        2           B
 4        3           B
 5        4           B
 6        4           E
 7        4           C
 8        5         'NULL'
 9        6           C

我想写一个查询来选择它:

ItemID    Supplier1    Supplier2    Supplier3 
  1           E
  2           E            B
  3           B
  4           B            E            C
  5           
  6           C

但我只能得到第一列:

SELECT ItemID, FIRST(ItemSupplier) AS Supplier1
FROM myTable GROUP BY ItemID

谢谢

【问题讨论】:

    标签: sql ms-access-2007


    【解决方案1】:

    MS Access 并不是最好的工具。

    一种方法使用相关子查询来枚举值,然后进行条件聚合:

    select itemid,
           max(iif(seqnum = 1, itemsupplier, null)) as supplier_1,
           max(iif(seqnum = 2, itemsupplier, null)) as supplier_2,
           max(iif(seqnum = 3, itemsupplier, null)) as supplier_3
    from (select t.*,
                 (select count(*)
                  from t as t2
                  where t2.itemid = t.itemid and t2.id <= t.id
                 ) as seqnum
          from t
         ) as t
    group by itemid;
    

    几乎所有其他数据库都支持窗口函数,这将提高效率。

    【讨论】:

    • 谢谢你完美的工作。在代码(VB.NET)中这样做会更有效吗?
    • @Adrien 。 . .如果您在(itemid, id) 上有一个索引,那么性能可能还可以。如果这解决了您的问题,您可以接受答案。
    • 知道了。这就是我上次要找的东西,但由于它并不明显,我认为我也没有足够的分数。再次感谢。
    猜你喜欢
    • 2014-08-16
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 2021-04-28
    • 2023-04-06
    • 2013-05-24
    • 1970-01-01
    • 2017-08-23
    相关资源
    最近更新 更多