编写 SQL 查询以将表从 A 转换为 B

Write a SQL query to convert table from A to B(编写 SQL 查询以将表从 A 转换为 B)
本文介绍了编写 SQL 查询以将表从 A 转换为 B的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 SQL Server 2016 中,我有一个数据库表(表 A)如下所示:

I have a database table (table A) looks like this, in SQL Server 2016:

表A:

ID     Group       2018     2019    2020
-----------------------------------------
ID1    Group A      200      300     400
ID2    Group B      100      800     ---
ID2    Group B      ----     500     300

我想编写一个 SQL 查询或类似的东西或报告工具来生成报告/表(将表 A 转换为表 B),如下所示:

I want to write a SQL query or something like that or a reporting tool to generate a report/table (convert table A to table B) as below:

表 B:

ID       Group   -   Year  -      Value
----------------------------------------
ID1      Group A     2018         200
ID1      Group A     2019         300
ID1      Group A     2020         400
ID2      Group B     2018         100
ID2      Group B     2019         800
ID2      Group B     2019         500
ID2      Group B     2020         300

如果可以通过编写 SQL 查询来实现,那就太好了.如果需要使用编程语言编写程序,或者使用工具,也可以,但请告诉我使用什么以及如何实现(我知道一些C#编程).

If it can be achieved by writing a SQL query that would be great. If that it needs to use a programming language to write a program, or use a tool, that will also be OK but please let me know what to use and how to achieve (I know some C# programming).

(我知道我不应该使用 ID 和 Group 作为列名.我不会在数据库表中真正使用那个名称,只是为了简化这里的问题)

(I know I should not use ID and Group as the column name. I will not really use that name in the database table, just to simplify the question here)

有人可以帮忙吗?非常感谢!

Anyone can help? Thank you very much!

推荐答案

使用union all的规范方法:

select id, group, 2018 as year, "2018" from t
union all
select id, group, 2019 as year, "2019" from t
union all
select id, group, 2020 as year, "2018" from t;

不过,在SQL Server中,我强烈推荐apply:

However, in SQL Server, I strongly recommend apply:

select t.id, t.group, v.*
from t cross apply
     (values (2018, [2018]), (2019, [2019]), (2020, [2020])
     ) v(year, value)
where v.value is not null;

这篇关于编写 SQL 查询以将表从 A 转换为 B的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)