Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL 2 Tables, get counts on first, group by second

I'm working in MS Access 2003.

I have Table with records of that kind of structure:

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 ...
...

I also have table which has Origin And Destination Codes Grouped

Code, Country, Continent
1000, Albania, Europe
1001, Belgium, Europe
...
1100, China,   Asia
1105, Japan,   Asia
...

What I need is to get 2 tables which would count records based on criteria related to attributes I specify but grouped by:
1. Origin Continent and Destination Continent
2. Origin Continent and Destination Country

for example:

Case 1.

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

Case 2.

Origin, Destination, Total, Females, Males, Older than 20, Younger than 20, ...
Europe, Asia,        1500,  700,     800 ...
Asia,   Europe,      1200, ...
...

Can that be done in the way so I could add more columns/criteria easily enough?

like image 882
user1155872 Avatar asked Nov 12 '22 17:11

user1155872


1 Answers

Case 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

Case 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
like image 181
ogres Avatar answered Nov 15 '22 07:11

ogres