[英]order by on mysql by count of one column
I have a table我有一张桌子
tid item
1 k1
1 k1
1 k1
1 k2
1 k2
2 k1
2 k3
3 k2
3 k1
3 k4
I want to order it from total item, so k1 appear 5 time,, than k2 appear 3 times, k3 and k4 once.我想从总项目中订购它,所以 k1 出现 5 次,比 k2 出现 3 次,k3 和 k4 一次。 I want to order it by tid asc, and count of item desc.
我想按 tid asc 和项目 desc 计数订购它。
I tried this query,我试过这个查询,
SELECT *
FROM `tes2`
order by count(id_item) desc
But it just returns 1 row.但它只返回 1 行。
tid item
1 k1
How to get all of the data?如何获取所有数据?
an output that i want is like this我想要的输出是这样的
tid item
1 k1
1 k1
1 k1
1 k2
1 k2
2 k1
2 k3
3 k1
3 k2
3 k4
so its ordered by the count of item.所以它按项目计数排序。
You can do this by using a subquery to get the count for each item and then join that to the main table on item so you can order by count.您可以通过使用子查询来获取每个项目的计数,然后将其连接到项目的主表中,以便您可以按计数订购。 Below is MSSQL but you should be able to use this solution in your MySQL query.
下面是 MSSQL,但您应该能够在 MySQL 查询中使用此解决方案。
Set up the test --设置测试——
DECLARE @Test TABLE
(
tid int,
tem VARCHAR(5)
)
INSERT into @Test (tid, item) VALUES (1, 'k1');
INSERT into @Test (tid, item) VALUES (1, 'k1');
INSERT into @Test (tid, item) VALUES (1, 'k1');
INSERT into @Test (tid, item) VALUES (1, 'k2');
INSERT into @Test (tid, item) VALUES (1, 'k2');
INSERT into @Test (tid, item) VALUES (2, 'k1')
INSERT into @Test (tid, item) VALUES (2, 'k3');
INSERT into @Test (tid, item) VALUES (3, 'k2');
INSERT into @Test (tid, item) VALUES (3, 'k1');
INSERT into @Test (tid, item) VALUES (3, 'k4');
Query --询问 -
SELECT t.tid,t.item
FROM @Test t
JOIN (SELECT t2.Item, COUNT(*) AS ItemCount FROM @Test t2 GROUP BY t2.Item) counts ON counts.Item = t.Item
ORDER BY counts.ItemCount DESC, t.tid ASC
OUTPUT --输出 -
tid item
1 k1
1 k1
1 k1
2 k1
3 k1
1 k2
1 k2
3 k2
2 k3
3 k4
try this:尝试这个:
SELECT count(id_item), field1, field2, field3
FROM `tes2`
order by 0 desc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.