您可以使用子查询来获取每个项目的计数,然后加入该主表上的项目,以便您可以通过计数命令做到这一点。 下面是MSSQL,但你应该能够在你的MySQL查询中使用这个解决方案。
设置测试 -
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');
查询 -
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
输出 -
tid item
1 k1
1 k1
1 k1
2 k1
3 k1
1 k2
1 k2
3 k2
2 k3
3 k4
来源
2016-05-06 13:31:49
Tom
尝试使用具有 – Mojtaba
请提供您的问题与表期望的输出。 – trincot
@trincot我已经添加它,THX的男人.. –