您可以使用子查詢來獲取每個項目的計數,然後加入該主表上的項目,以便您可以通過計數命令做到這一點。 下面是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的男人.. –