我有这张桌子。
id | item_id | created_at
-----+-----------+------------
1 | Apple | 2017-03-21
2 | Grape | 2017-03-23
3 | Grape | 2017-03-24
4 | Apple | 2017-03-25
我想通过 created_at 订购,同时也可以通过 item_id 订购:
id | item_id | created_at
-----+-----------+------------
4 | Apple | 2017-03-25
1 | Apple | 2017-03-21
3 | Grape | 2017-03-24
2 | Grape | 2017-03-23
因此,如果我为 item_id添加新行:Grape ,我的新结果应如下所示:
id | item_id | created_at
-----+-----------+------------
5 | Grape | 2017-03-28 (NEW)
3 | Grape | 2017-03-24
2 | Grape | 2017-03-23
4 | Apple | 2017-03-25
1 | Apple | 2017-03-21
然后如果我为 item_id添加新行:Apple ,它应该是这样的:
id | item_id | created_at
-----+-----------+------------
6 | Apple | 2017-03-28 (NEW)
4 | Apple | 2017-03-25
1 | Apple | 2017-03-21
5 | Grape | 2017-03-27
3 | Grape | 2017-03-24
2 | Grape | 2017-03-23
...所以它按最新的 created_at 排序,并在其下方显示其他行 item_id
我已经尝试了ORDER BY created_at, item_id DESC
,但它不起作用而是给我这个:
id | item_id | created_at
-----+-----------+------------
6 | Apple | 2017-03-28
5 | Grape | 2017-03-27
4 | Apple | 2017-03-25
3 | Grape | 2017-03-24
2 | Grape | 2017-03-23
1 | Apple | 2017-03-21
答案 0 :(得分:2)
您需要首先确定您的第一条规则,即created_at
每item_id
个item_id
,因此添加了row_number()
并添加了SELECT tt.id, tt.item_id, tt.created_at
FROM test_table tt
INNER JOIN
(SELECT item_id,
MAX(created_at),
ROW_NUMBER() OVER (ORDER BY MAX(created_at) DESC) rn
FROM test_table
GROUP BY item_id
ORDER BY 3) ord
ON tt.item_id = ord.item_id
ORDER BY ord.rn, tt.created_at DESC;
的子查询,以便它可以知道哪种水果首先出现。然后加入你的桌子。
googlenews <- WebCorpus(GoogleNewsSource("Microsoft"))
Unknown IO errorfailed to load external entity "http://news.google.com/news?hl=en&q=Microsoft&ie=utf-8&num=100&output=rss"
Error: 1: Unknown IO error2: failed to load external entity "http://news.google.com/news?hl=en&q=Microsoft&ie=utf-8&num=100&output=rss"
library(tm.plugin.webmining)
library(purrr)
company <- c("Microsoft", "Apple", "Google", "Amazon", "Facebook",
"Twitter", "IBM", "Yahoo", "Netflix")
symbol <- c("MSFT", "AAPL", "GOOG", "AMZN", "FB", "TWTR", "IBM", "YHOO", "NFLX")
download_articles <- function(symbol) {
WebCorpus(GoogleFinanceSource(paste0("NASDAQ:", symbol)))
}
stock_articles <- data_frame(company = company,
symbol = symbol) %>%
mutate(corpus = map(symbol, download_articles))
failed to load HTTP resource
Error in mutate_impl(.data, dots) : 1: failed to load HTTP resource
答案 1 :(得分:2)
WITH grouped AS (
select item_id, max(created_at) as max_dt
from tbl
group by item_id
)
SELECT tbl.*
FROM grouped
LEFT JOIN tbl USING (item_id)
ORDER BY grouped.max_dt desc,
grouped.item_id, -- important if apple and grape both have same max dt
tbl.created_at desc;
答案 2 :(得分:1)
答案 3 :(得分:0)
答案 4 :(得分:0)
这是一个mysql版本
set @ordr = 0;
select t.*
from tbl t
join (
select o.item_id, o.created_at, @ordr := @ordr + 1 as `order`
from (
select tbl.item_id, max(tbl.created_at) as created_at
from tbl
group by tbl.item_id
order by created_at desc
) as o
) sub
on t.item_id = sub.item_id
order by sub.`order`, sub.created_at desc