sql—如何从两个表中查询数据并按两列分组

hof1towb  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(371)

我使用的是sql server,我有两个包含各种数据的巨大表。我想检索每个城市有多少拉脱维亚人或俄罗斯人居住的数据。
语言栏包含两种以上的语言,但我只想查询“拉脱维亚语”和“俄语”
表1(值得一提的列):

ID
ProjectID
Phone_nr
City

表2(值得一提的列):

ID
ProjectID
Phone_nr
Language

我希望查询检索如下信息:

City1(RU) | Amount of Russians
City1(LT) | Amount of Latvians
City2(RU) | Amount of Russians
City2(LT) | Amount of Latvians
.. etc

或者类似的:

City1 | Amount of Russians | Amount of Latvians  | Total amount of people
City2 | Amount of Russians | Amount of Latvians  | Total amount of people
City3 | Amount of Russians | Amount of Latvians  | Total amount of people
.. etc

我想知道什么是最好的解决办法?我应该用吗 join 或者 union 或者一个简单的 select ?
我提出了这样一个问题:

SELECT DISTINCT top 100 t.city, count(t.city) as 'Total amount of nr in city', count(*), l.language
FROM table1 l, table2 t
WHERE l.phone = t.phone and l.projectID = t.projektID
group by t.city, l.language

我相信 where 子句是正确的,因为两个表都有电话号码和项目ID,所以查询必须使用where子句进行选择。不幸的是,这不太管用。它以以下格式返回行:

City1 | Amount of y | total amount of numbers in this language
City1 | Amount of x | total amount of numbers in that language

很接近,但还不够好。注意:我正在使用 select top 100 只是为了测试,我会选择一切,一旦我做了正确的查询。
有人能帮我或给我指出正确的方向吗?谢谢您

mctunoxg

mctunoxg1#

您可以尝试使用条件聚合-

SELECT t.city, 
count(case when l.language='Russians' then 1 end) as 'Amount of Russians',
count(case when l.language='Latvians' then 1 end) as 'Amount of Latvians',
count(*) as 'Total amount of nr in city'
FROM table1 l inner join table2 t
on l.phone = t.phone and l.projectID = t.projektID
group by t.city

注意:最好显式地使用join。

e0bqpujr

e0bqpujr2#

@fahmi的逻辑是正确的。还有一种方法是使用sum而不是count。我增加了额外的选项来考虑。

SELECT t.city, 
SUM(case when l.language='Russians' then 1 else 0 end) as 'Amount of Russians',
SUM(case when l.language='Latvians' then 1  else 0 end) as 'Amount of Latvians',
count(*) as 'Total amount of nr in city'
FROM table1 l inner join table2 t
on l.phone = t.phone and l.projectID = t.projektID
group by t.city

相关问题