第一列记录中需要显示的第1列需要排序的数据,其余记录则不需要。我可以用boolean添加另一列以确定哪个是第一条记录。所需的结果如下。
+--------+------------+-------+
| type | variety | price |
+--------+------------+-------+
| apple | gala | 2.79 |
| | fuji | 0.24 |
| | limbertwig | 2.87 |
| orange | valencia | 3.59 |
| | navel | 9.36 |
| pear | bradford | 6.05 |
| | bartlett | 2.14 |
| cherry | bing | 2.55 |
| | chelan | 6.33 |
+--------+------------+-------+
答案 0 :(得分:1)
NA
自从我做了这样的事情已经有一段时间了,但这是总的想法。
gamble <- function(k, n, p) {
stake <- rep(NA_real_, 1e4)
i <- 1
stake[1] <- k
while (stake[i] > 0 & stake[i] < n) {
bet <- sample(c(-1, 1), 1, prob = c(1 - p, p))
stake[i + 1] <- stake[i] + bet
i <- i + 1
if (length(stake) == i) stake <- c(stake, rep(NA_real_, 1e4))
}
return(stake[!is.na(stake)])
}
k <- 6
n <- 10
p <- 1 / 2
trials <- 100
simlist <- replicate(trials, gamble(k, n, p))
head(simlist)
# [[1]]
# [1] 6 5 4 3 4 3 2 1 0
#
# [[2]]
# [1] 6 7 6 5 6 5 4 3 2 3 4 3 4 5 4 5 4 5 6 7 8 7 8 7 6 7 8 7
# [29] 8 9 8 7 6 7 6 7 8 9 10
#
# [[3]]
# [1] 6 5 4 3 2 1 0
#
# [[4]]
# [1] 6 7 8 9 8 7 6 5 6 5 4 5 6 7 6 7 6 5 4 3 2 3 2 3 4 3 2 1 2 1 0
#
# [[5]]
# [1] 6 5 6 5 4 3 4 3 2 3 4 3 4 3 4 3 4 3 4 5 4 5 6 5 6 7 6 5 4 5 4 5 4 3 4 3 2 1 2 1 2 3
# [43] 2 3 2 3 2 1 0
#
# [[6]]
# [1] 6 7 6 7 8 7 6 7 8 9 10
子查询仅用于初始化@prev会话变量。SELECT `type`, `variety`, `price`
FROM (
SELECT IF(@prev != t.`type`, t.`type`, '') AS `type`
, t.`variety`, t.`price`
, @prev := t.`type` AS actualType
FROM theTable AS t
CROSS JOIN (SELECT @prev := '') AS init
ORDER BY t.`type`, t.`variety`, t.`price`
) AS subQ
的表达式将为处理的下一行更新@prev会话变量。init
中,以确保在涉及@prev的表达式之后不应用它。答案 1 :(得分:0)
正如其他人提到的那样,最好在客户端中完成,因为这是一个演示问题,但是您可以使用ROW_NUMBER窗口函数和CASE语句从技术上实现所需的内容。我没有方便的MYSQL实例,但是以下应该可以工作。
WITH T as (
SELECT
ROW_NUMBER() OVER ( PARTITION BY type ORDER BY 1 ) rownum,
type,
variety,
price
FROM products )
SELECT
CASE WHEN rownum = 1 THEN type ELSE '' END type,
variety,
price
FROM t;