我有三张桌子
tbl_worker
City WorkerName Job
10 Raymond Carpenter
10 Sara Programmer
11 John Painter
11 Alice Booker
tbl_workshop
City WorkshopName
10 Dell
11 Apple
10 Sony
Tbl_city
Id Name
10 Mexico
11 Sydney
现在我想要这样的结果:
City WorkersQty WorkshopQry
Mexico 2 2
Sydney 2 1
结果返回在不同城市注册的工人和工作坊的数量。 我应该写什么查询?
答案 0 :(得分:2)
分别对tbl_workshop
和tbl_worker
表进行分组,然后使用LEFT JOIN
获取结果:
SELECT c.City,
k.Cnt AS WorkersQty,
w.Cnt AS WorkshopQry
FROM Tbl_city c
LEFT JOIN (
SELECT City, COUNT(*) Cnt
FROM tbl_worker
GROUP BY City
) k ON c.ID = k.City
LEFT JOIN (
SELECT City, COUNT(*) Cnt
FROM tbl_workshop
GROUP BY City
) w ON c.ID = w.City
如果您只想显示有工作室或工作人员的城市,请添加:
WHERE k.Cnt > 0 OR w.Cnt > 0
答案 1 :(得分:0)
使用Dense_rank获取研讨会或工作人员的数量
SELECT city, MAX(WorkshopQty) AS WorkshopQty , MAX(WorkersQty) AS WorkersQty
FROM (
SELECT c.name AS City,
DENSE_RANK() OVER (PARTITION BY c.id ORDER BY WorkshopName) AS WorkshopQty,
DENSE_RANK() OVER (PARTITION BY c.id ORDER BY WorkerName) AS WorkersQty
FROM tbl_city c
INNER JOIN tbl_workshop s ON s.city = c.id
INNER JOIN tbl_worker w ON w.city = c.id
) s
GROUP BY City