[英]sql group query with order by and limit
我的表結構如下
| id | cmp | empid | empname | ttm
+------+----------+-------+---------+------
| 2 | xyz | 12 | swap | 2
| 2 | xyz | 12 | sag | 3
| 2 | xyz | 14 | azr | 1
| 3 | pqr | 2 | ron | 2
| 3 | pqr | 22 | rah | 1
| 3 | pqr | 32 | pra | 5
我已經完成了如下查詢
(select * from test.companies where id = '2' order by ttm desc limit 2)
union
(select * from test.companies where id = '3' order by ttm desc limit 2);
它會給 output 如下
| id | cmp | empid | empname | ttm
+------+----------+-------+---------+------
| 2 | wissen | 12 | sag | 3
| 2 | wissen | 12 | swap | 2
| 3 | prolinkd | 32 | pra | 5
| 3 | prolinkd | 2 | ron | 2
但我想要 output 如下
| id | cmp | empid | empname | ttm
+------+----------+-------+---------+------
| 3 | prolinkd | 32 | pra | 5
| 3 | prolinkd | 2 | ron | 2
| 2 | wissen | 12 | sag | 3
| 2 | wissen | 12 | swap | 2
表示哪家公司擁有最大 ttm 它將首先顯示
如果有人知道請回復
謝謝
相當丑陋的外觀和丑陋的聲音,但它應該做你想要的。 它使用每條記錄檢索每個公司的“maxttm”,然后在排序中使用它來允許您根據公司的最高 ttm 為其分配優先級。
SELECT * FROM (
(SELECT *,
(SELECT ttm FROM test.companies ic WHERE ic.id = oc.id ORDER BY ttm DESC LIMIT 1) AS maxttm
FROM test.companies oc WHERE id = '2' ORDER BY ttm DESC LIMIT 2)
UNION
(SELECT *,
(SELECT ttm FROM test.companies ic WHERE ic.id = oc.id ORDER BY ttm DESC LIMIT 1) AS maxttm
FROM test.companies oc WHERE id = '3' ORDER BY ttm DESC LIMIT 2)
) AS myunion ORDER BY maxttm, id;
PS。 感謝 inti 我無恥地以此為基礎的查詢。
我認為這會起作用:
SELECT * FROM (
(select * from test.companies where id = '2' order by ttm desc limit 2)
union
(select * from test.companies where id = '3' order by ttm desc limit 2)
) as myunion ORDER BY ttm;
得到你需要的東西,並通過 ttm 訂購。
select *
from test.companies
where id in ('2','3')
and ttm > 1
order by ttm desc, id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.