SQL 2表,首先获取计数,然后分组

SQL 2表,首先获取计数,然后分组,sql,database,ms-access,Sql,Database,Ms Access,我在微软Access 2003工作 我有一张表格,上面有这种结构的记录: ID, Origin, Destination, Attr1, Attr2, Attr3, ... AttrX for example: 1, 1000, 1100, 20, M, 5 ... 2, 1000, 1105, 30, F, 5 ... 3, 1001, 1000, 15, M, 10 ... ... 我

我在微软Access 2003工作

我有一张表格,上面有这种结构的记录:

ID, Origin, Destination, Attr1, Attr2, Attr3, ... AttrX

for example:

1,  1000,   1100,        20,    M,     5 ...
2,  1000,   1105,        30,    F,     5 ...
3,  1001,   1000,        15,    M,     10 ...
...
我还有一个表,其中包含分组的源代码和目标代码

Code, Country, Continent
1000, Albania, Europe
1001, Belgium, Europe
...
1100, China,   Asia
1105, Japan,   Asia
...
我需要的是得到两个表,它们将根据与我指定的属性相关的条件对记录进行计数,但按以下方式分组:
1.起始大陆和目的大陆
2.始发大陆和目的地国

例如:

案例1.

Origin, Destination, Total, Females, Males, Older than 20, Younger than 20, ...
Europe, China,       300,   100,     200,   120,           180 ...
Europe, Japan,       150,   100,     50, ...
...
案例2.

Origin, Destination, Total, Females, Males, Older than 20, Younger than 20, ...
Europe, Asia,        1500,  700,     800 ...
Asia,   Europe,      1200, ...
...
可以这样做吗?这样我就可以很容易地添加更多的列/标准了?

案例1:

select count(1) as total ,t2.continent,t3.country,t1.attr1,t1.attr2,t1.attr3 ... t1.attrX from table1 t1
join table2 t2 on t1.origin = t2.code
join table3 t3 on t1.destination = t3.code
group by t2.continent,t3.country,t1.attr1,t1.attr2,t1.attr3 ... t1.attrX 
order by total desc
案例2:

select count(1) as total ,t2.continent,t3.continent,t1.attr1,t1.attr2,t1.attr3 ... t1.attrX from table1 t1
join table2 t2 on t1.origin = t2.code
join table3 t3 on t1.destination = t3.code
group by t2.continent,t3.continent,t1.attr1,t1.attr2,t1.attr3 ... t1.attrX 
order by total desc

您可以将查询与查询连接起来,因此这是一个男性/女性的交叉表(attr2)

这是:

TRANSFORM Count(Data.ID) AS CountOfID
SELECT Data.Origin, Data.Destination, Count(Data.ID) AS Total
FROM Data
GROUP BY Data.Origin, Data.Destination
PIVOT Partition([Attr1],10,100,10);
这将两者结合起来:

SELECT Ages.Origin, Ages.Destination, Ages.Total,
       MF.F, MF.M, Ages.[10: 19], Ages.[20: 29], Ages.[30: 39]
FROM Ages, MF;

如您所见,这在VBA中更易于管理。

在类似的情况下,我使用了一个表单,允许用户选择条件并在VBA中生成查询。我不确定您是否会得到令人满意的纯sql解决方案。请注意,标记包括MS Access,sql是一个通用标记,因此此特定答案需要MS Access sql。上述方法行不通。我不知道如何使用此答案对属性应用标准以获得特定计数。access也会在FROM子句中抛出语法错误。您应该在select和group by中添加属性,当然它也会抛出错误,语句中有…-s
SELECT Ages.Origin, Ages.Destination, Ages.Total,
       MF.F, MF.M, Ages.[10: 19], Ages.[20: 29], Ages.[30: 39]
FROM Ages, MF;