【问题标题】:SQL 2 Tables, get counts on first, group by secondSQL 2表,首先获得计数,按秒分组
【发布时间】:2012-11-23 10:33:29
【问题描述】:

我正在使用 MS 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
...

我需要的是获得 2 个表,这些表将根据与我指定的属性相关的条件对记录进行计数,但按以下条件分组:
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, ...
...

是否可以这样做,以便我可以轻松地添加更多列/标准?

【问题讨论】:

  • 在类似的情况下,我使用了一个允许用户选择条件并在 VBA 中构建查询的表单。我不确定你会得到一个令人满意的纯 sql 解决方案。

标签: sql database ms-access


【解决方案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

【讨论】:

  • 请注意标签包括MS Access,SQL是通用标签,所以这个特定的答案需要MS Access SQL。以上将不起作用。
  • 我看不到如何对属性应用标准以使用此答案获取特定计数。也访问在 FROM 子句中抛出语法错误。
  • 你也应该在select和group by中添加你的属性,当然会报错,语句中有...-s
【解决方案2】:

您可以将查询与查询连接起来,因此这是男性/女性 (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 Data.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 中可能更容易管理。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-15
    • 1970-01-01
    • 2022-01-08
    • 2019-11-26
    • 2020-02-10
    相关资源
    最近更新 更多