我的数据库看起来像这样
数据:
ID | Number | A | Version
1 | N123 | K | 1
2 | N123 | O | 1
3 | N123 | O | 2
4 | N123 | K | 2
5 | N234 | K | 1
6 | N234 | O | 1
7 | N456 | K | 1
8 | N456 | L | 1
9 | N456 | K | 2
10 | N456 | L | 2
我的结果应如下所示:
Number | A | Version
N123 | O, K | 2
N234 | O, K | 1
N456 | K, L | 2
这意味着我有一个表格,其中包含与数字(和版本)相关的重复条目。例如:N123在版本1中存在两次。一次是A = K,一次是A = O.合并我有N123(V1),K = A和O.此捆绑包在版本2中有重复。 我要查询的是最高版本和K的组合,以便我不再有重复的条目。
顺便提一下,数据是来自更大数据源的查询的结果。也许解决方案可以在这个初始查询中:
SELECT Data.[Number], Data.[Version], Data.[K]
FROM Data
WHERE (((Data.[Number]) In (SELECT [Number] FROM [Data] As Tmp GROUP BY [Number],[Version] HAVING Count(*)>1 And [Version] = [Data].[Version])))
ORDER BY Data.[Number], Data.[Version];
答案 0 :(得分:1)
使用GROUP_CONCAT
和CONCAT
函数以及MAX
和GROUP BY
来实现此目标。
SELECT Number,
GROUP_CONCAT(A) AS A,
MAX(Version) AS Version
FROM data
WHERE CONCAT(Version,'-',Number) IN (SELECT CONCAT(MAX(Version),'-',Number) FROM data GROUP BY Number)
GROUP BY Number
ORDER BY Number
输出
Number A Version
N123 O,K 2
N234 K,O 1
N456 K,L 2
答案 1 :(得分:0)
当我在评论中说,为了OleDb目的没有解决方案,我假设[A]包含一些未知(和无限)的可能性。但是,如果[A]实际上是枚举,则可以在没有自编函数帮助的情况下使用SQL在MS Access中实现串联。您可以使用一系列LEFT JOINS来执行此操作:
SELECT Number, ConcatKLO, MAX(version) AS MaxVersion FROM
(SELECT number, version, left(ConcatA,Len(ConcatA) -2) as ConcatKLO FROM
(SELECT d.number, d.version, IIF(k.A IS NULL, "",k.A + ", ") + IIF(l.A IS NULL, "",l.A + ", ") + IIF(o.A IS NULL, "",o.A + ", ") AS ConcatA FROM
(((SELECT DISTINCT number, version FROM Data) as d
LEFT JOIN
(SELECT number, A, version FROM Data WHERE A = 'K') as k
ON d.number = k.number and d.version = k.version)
LEFT JOIN
(SELECT number, A, version FROM Data WHERE A = 'O') as o
ON d.number = o.number and d.version = o.version)
LEFT JOIN
(SELECT number, A, version FROM Data WHERE A = 'L') as l
ON d.number = l.number and d.version = l.version) as c) as a
GROUP BY Number, concatklo
来自OleDB的调用问题是,您只能使用Access引擎中内置的函数。