如何根据其他表中其他列的频率
从一个表中选择列示例:
Table 1
sr. id
1 37
2 45
3 56
3 69
2 25
Table 2
id
37
45
56
56
56
45
69
预期结果
sr count
1 1
2 2
3 4
现在我需要按sr
中其ID的频率顺序选择table 2
。
答案 0 :(得分:1)
以下查询可以完成您想要的任务:
SELECT
Table1.sr,
COUNT(*) total
FROM Table1
INNER JOIN Table2
ON Table1.id = Table2.id
GROUP BY Table1.sr
ORDER BY total;
更多强>
以防万一,如果您想要sr
中的所有table1
,无论table2
中是否存在相应的ID,那么您需要使用LEFT JOIN
。< / p>
所以,这里是基于这种情况的修改过的查询:
SELECT
Table1.sr,
COUNT(Table2.id) total
FROM Table1
LEFT JOIN Table2
ON Table1.id = Table2.id
GROUP BY Table1.sr
ORDER BY total;
答案 1 :(得分:0)
这样的事情:
SELECT t1.sr, t1.id
FROM table1 AS t1
JOIN (
SELECT id, COUNT(*) AS cnt
FROM table2
GROUP BY id
) AS t2 ON t1.id = t2.id
ORDER BY t2.cnt DESC
答案 2 :(得分:0)
select t1.sr,count(*)
from take1 t1
inner join take2 t2 on t1.id =t2.id
group by t1.sr