sql - 如何以自定义格式检索数据
问题描述
- 我检索到一些数据如下(图 01)。
我使用了这个查询:
SELECT TOP (3) no, co, cdate, year
FROM main_backup
WHERE (no = 41505)
ORDER BY cdate DESC
- 但我想要那个,就像下面的这种类型(图片02)
解决方案
您可以使用条件聚合和窗口函数:
select no,
max(case when seqnum = 1 then total end) as total_1,
max(case when seqnum = 1 then cdate end) as date_1,
max(case when seqnum = 2 then total end) as total_2,
max(case when seqnum = 2 then cdate end) as date_2,
max(case when seqnum = 3 then total end) as total_3,
max(case when seqnum = 3 then cdate end) as date_3
from (select t.*,
row_number() over (partition by no order by cdate desc) as seqnum
from t
) t
group by no
推荐阅读
- c++ - 虚拟继承构造函数的组装
- sql - 如何遍历在嵌套 Oracle SQL 查询中选择的记录并根据特定条件在外部选择中选择它们
- sql - 我不能在 Oracle 中使用 min 和 max
- symfony - 为 HttpFoundation/response 返回 Null
- python - 为什么 Python zipfile 不提供与命令行 zip 相同的输出 .zip 文件大小?
- elasticsearch - 使用 NEST 设置 Elasticsearch routing_partition_size
- elasticsearch - 仅来自唯一值的 Date_histogram 和 top_hits
- graphql - 使用 Apollo Server 运行 Jest 失败 global.fetch undefined
- java - 反转屏幕,包括 null 和空字符串
- java - 使用自定义容器作为数据库与 TestContainer