sql - 如何在不同的列中选择第一个、第二个和第三个值 - Ms Access
问题描述
我在表格中有这些数据:
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
谢谢
解决方案
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;
几乎所有其他数据库都支持窗口函数,这将提高效率。
推荐阅读
- mvvm - 如何检测listview xamarin表单中的可点击标签位置
- javascript - js中的var char不起作用
- laravel - 如何检查表单输入是否有文件 laravel?
- php - Ubuntu/Apache2 更改 PHP 版本
- gensim - Gensim Doc2Vec - 为什么 infer_vector() 使用 alpha?
- java - Java -> Kotlin。数据类转换模式
- json - 如何在 Web API 中返回嵌套的 TreeView JSON
- php - 动态查询 DROP mysql 触发器
- python - 如何在python中打印具有相等间距的同一行中的两个单词
- java - 带有quartz作业调度程序的spring MVC WebApp