不明确的列和计数
Ambiguous Columns and Count
我的查询要求我按人数找到最繁忙的位置(附加架构)
select DISTINCT location.name as 'Location', f_name|| ' ' || l_name as 'Citizen'
from CheckIn
join location on checkin.LocID = Location.LocID
join person on person.PersonID = CheckIn.PersonID
有了上面的查询。我可以找到访问过这些地点的人,但我找不到访问过某个地点的最多人数,因为他们都单独显示。我知道我需要添加计数或分组依据。
如果我尝试按照下面的方式进行计数
select DISTINCT location.name as 'Location', f_name|| ' ' || l_name as 'Citizen', count (personid)
from CheckIn
join location on checkin.LocID = Location.LocID
join person on person.PersonID = CheckIn.PersonID
它会给我显示模棱两可的栏目。我知道这是在说因为我已经将它用作连接但是如果我不能重用它我该如何计算人数?
如何修复此代码以按人数显示最繁忙的位置?
这个查询:
SELECT LID, COUNT(*)
FROM CheckIn
GROUP BY LID
returns 访问人数各LID
.
您还可以使用 window 函数 RANK()
根据人数对每个位置进行排名:
SELECT LID, RANK() OVER (ORDER BY COUNT(*) DESC) rnk
FROM CheckIn
GROUP BY LID
最后,您将此查询与运算符 IN
一起使用,以 return 排名第一的位置的详细信息:
SELECT * FROM Location
WHERE LocationID IN (
SELECT LID
FROM (
SELECT LID, RANK() OVER (ORDER BY COUNT(*) DESC) rnk
FROM CheckIn
GROUP BY LID
)
WHERE rnk = 1
)
您可以尝试以下操作:
select
name, COUNT(P.PersonID) as People_Count
from Location AS L
inner join checkin as C on C.LocID = L.LocID
inner join person as P on P.PersonID = C.PersonID
group by name
order by COUNT(P.PersonID) desc
我的查询要求我按人数找到最繁忙的位置(附加架构)
select DISTINCT location.name as 'Location', f_name|| ' ' || l_name as 'Citizen'
from CheckIn
join location on checkin.LocID = Location.LocID
join person on person.PersonID = CheckIn.PersonID
有了上面的查询。我可以找到访问过这些地点的人,但我找不到访问过某个地点的最多人数,因为他们都单独显示。我知道我需要添加计数或分组依据。
如果我尝试按照下面的方式进行计数
select DISTINCT location.name as 'Location', f_name|| ' ' || l_name as 'Citizen', count (personid)
from CheckIn
join location on checkin.LocID = Location.LocID
join person on person.PersonID = CheckIn.PersonID
它会给我显示模棱两可的栏目。我知道这是在说因为我已经将它用作连接但是如果我不能重用它我该如何计算人数?
如何修复此代码以按人数显示最繁忙的位置?
这个查询:
SELECT LID, COUNT(*)
FROM CheckIn
GROUP BY LID
returns 访问人数各LID
.
您还可以使用 window 函数 RANK()
根据人数对每个位置进行排名:
SELECT LID, RANK() OVER (ORDER BY COUNT(*) DESC) rnk
FROM CheckIn
GROUP BY LID
最后,您将此查询与运算符 IN
一起使用,以 return 排名第一的位置的详细信息:
SELECT * FROM Location
WHERE LocationID IN (
SELECT LID
FROM (
SELECT LID, RANK() OVER (ORDER BY COUNT(*) DESC) rnk
FROM CheckIn
GROUP BY LID
)
WHERE rnk = 1
)
您可以尝试以下操作:
select
name, COUNT(P.PersonID) as People_Count
from Location AS L
inner join checkin as C on C.LocID = L.LocID
inner join person as P on P.PersonID = C.PersonID
group by name
order by COUNT(P.PersonID) desc