[加分了!] 请教一个SQL行转列及动态字段的问题,谢谢。

[大楚] [大楚] 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区

--建表
create table Family
(
FID int primary key,
ParentName varchar(20),
Addr varchar(50)
)



create table Children
(
CID int identity(1,1) primary key,
FID int,
ChildName varchar(20),
Age int,
)


--测试数据
insert into Family (FID, ParentName,Addr) values (1, '张三', '中华大街');
insert into Family (FID, ParentName,Addr) values (2, '李四', '云海南路');
insert into Family (FID, ParentName,Addr) values (3, '王五', '和平小巷');


insert into Children (FID, ChildName,Age) values (1, '张小', 10);

insert into Children (FID, ChildName,Age) values (2, '李一', 8);
insert into Children (FID, ChildName,Age) values (2, '李二', 12);

insert into Children (FID, ChildName,Age) values (3, '王龙', 13);
insert into Children (FID, ChildName,Age) values (3, '王虎', 10);
insert into Children (FID, ChildName,Age) values (3, '王凤', 7);




查询语句:
select a.FID, ParentName, Addr, ChildName, Age from Family a, Children b where a.FID = b.FID and a.FID <= 3

查询结果
FID ParentName Addr ChildName Age
1 张三 中华大街 张小 10
2 李四 云海南路 李一 8
2 李四 云海南路 李二 12
3 王五 和平小巷 王龙 13
3 王五 和平小巷 王虎 10
3 王五 和平小巷 王凤 7



希望得到这样的查询结果:
FID ParentName Addr ChildName Age ChildName Age ChildName Age
1 张三 中华大街 张小 10
2 李四 云海南路 李一 8 李二 12
3 王五 和平小巷 王龙 13 王虎 10 王凤 7


当 a.FID <= 2 时, ChildName和Age列重复两次, 字段不足的记录空白。
实际上的要求是:动态列的增加是根据 Children 表中相同 FID 记录的最大数量来增加的,
而 Children 表中相同 FID 值的记录数量是不固定的

在Winform中应用,也可以考虑使用DataTable等相关组件,要求查询效率高,谢谢!








...全文

相关推荐

oracle动态行转列

用存储过程写的动态行转列。简单易用,查询速度高效

mikehaifei

SQL行转列的动态生成实践指南

PIVOT操作是SQL中的一个非常实用的特性,用于将行格式的数据转换为列格式。通过PIVOT,可以将某个列的多个值按照特定的聚合函数转换为多个列,从而实现数据透视的目的。这种方式对于数据的可视化和报告生成特别有用,因为它能够让数据以更加直观的方式呈现。举例来说,假设有一个销售数据表,其中包含产品、地区和销售量的记录,使用PIVOT可以快速将地区的不同销售量转换为列,从而直接比较各个地区的销售情况。PIVOT操作将复杂的行转列操作转化为一条SQL语句,这大大简化了数据处理过程。

EdTechIH

sql动态行转列的两种方法

第一种方法: 代码如下:select *from ( select Url,case  when  Month=01 then  ‘1月’ when  Month=02 then ‘2月’ when  Month=03 then  ‘3月’ when  Month=04 then ‘4月’ when  Month=05 then  ‘5月’ when  Month=06 then ‘6月’ when  Month=07 then  ‘7月’ when  Month=08 then ‘8月’ when  Month=09 then  ‘9月’ when  Month=10 then ‘ 10月’

weixin_38635092

mysql复杂动态行转列解决方案

NULL 博文链接:https://pmandy-163-com.iteye.com/blog/789326

weixin_38669628

SQL中如何实现行转列,列转行的操作

SQL中如何实现行转列,列转行的操作.这里的例子保证让你豁然开朗!

流鼻涕
评论 40
收藏 已收藏
分享
返回顶部
[大楚]
C# 111,130 成员 642,541 内容