我有一个访问数据库,格式如下:
ID | Period | Data
---------------------
13 | 1 | xxxxx
13 | 2 | xxxxx
25 | 1 | xxxxx
25 | 2 | xxxxx
25 | 3 | xxxxx
52 | 1 | xxxxx
52 | 3 | xxxxx
94 | 1 | xxxxx
94 | 2 | xxxxx
94 | 3 | xxxxx
期间可以是1,2或3.我需要计算期间为1,2和3,或期间1和2,或1和3的ID(它们始终具有期间) 1)。如何运行这样的查询 - 它可以是3个不同的查询来命中不同的排列。结果如下:
期间1,2和3: 数:2 (对于ID 25和94,虽然我不一定需要返回ID,只需要计数)
期间1和2: 数量:1(ID 13)
期间1和3: 数量:1(ID 52)
Access可以实现吗?它不是非常明显的值,因此this question和linked article似乎没有提供足够的帮助。我还没有数据库,这就是为什么我无法测试该查询,但我想知道在创建表之前是否可行,或者我是否需要找到另一种解决方案。
答案 0 :(得分:1)
创建像这样的转换查询并保存它的最简单方法
TRANSFORM Count(YourTable.ID) AS CountOfID
SELECT YourTable.ID
FROM YourTable
GROUP BY YourTable.ID
PIVOT YourTable.Period)
哪个输出
ID 1 2 3
-- - - -
13 1 1
25 1 1 1
52 1 1
94 1 1 1
然后您可以使用它创建另一个查询Lke this
SELECT t.Groups, Count(t.ID) AS CountOfID
FROM (SELECT ID,
SWITCH(
[1] = 1 and [2] =1 and [3] = 1, 'Periods 1, 2, and 3',
[1] = 1 and [2] =1 , 'Periods 1 and 2',
[1] = 1 and [3] =1 , 'Periods 1 and 3'
) as Groups
FROM TheSavedTransformQuery) AS t
GROUP BY t.Groups;
哪个输出
Groups CountOfID
------------------- ---------
Periods 1 and 2 1
Periods 1 and 3 1
Periods 1, 2, and 3 2
如果您想将其作为单个SQL语句执行,那么它也可以正常工作
SELECT
t.Groups,
Count(t.ID) AS CountOfID
FROM (
SELECT
Switch(
FirstPeriod.Period=1 And [SecondPeriod.Period ]=2 And [ThirdPeriod.Period]=3,'Periods 1, 2, and 3',
FirstPeriod.Period=1 And [SecondPeriod.Period]=2,'Periods 1 and 2',
FirstPeriod.Period=1 And [ThirdPeriod.Period]=3,'Periods 1 and 3') AS Groups,
DistinctID.ID
FROM (((SELECT DISTINCT ID
FROM
YourTable ) AS DistinctID
LEFT JOIN (SELECT ID, PERIOD
FROM YourTable
WHERE Period = 1) AS FirstPeriod
ON DistinctID.ID = FirstPeriod.ID)
LEFT JOIN (SELECT ID, PERIOD
FROM YourTable WHERE Period = 2) AS SecondPeriod
ON DistinctID.ID = SecondPeriod.ID)
LEFT JOIN (SELECT ID, PERIOD
FROM YourTable
WHERE Period = 3) AS ThirdPeriod
ON DistinctID.ID = ThirdPeriod.ID
)AS t
GROUP BY
t.Groups