一次查询多条合并到一条记录的问题

youlooklook 2007-01-05 11:21:52
我有两个表,结构大致如下:

A表

字段 类型 含义
DataValue float 数据值
DataKind int 数据种类 范围 0-7 分别代表一组数据的8个数据指标
DataTime datetime 数据时间


如上所示,每组数据要包含8种数据指标,但是在数据库里为8条记录,能不能通过SQL将A表中的内容合成一条记录,分别赋予它不同的字段名称。
...全文
366 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
marco08 2007-01-05
  • 打赏
  • 举报
回复
--這樣?
create table T(id int, type int)
insert T select 1, 1
union all select 1, 2
union all select 1, 3
union all select 2, 3

select id,
'A'=max(case type when 1 then 1 end),
'B'=max(case type when 2 then 2 end),
'C'=max(case type when 3 then 3 end)
from T
group by id

--result
id A B C
----------- ----------- ----------- -----------
1 1 2 3
2 NULL NULL 3

(2 row(s) affected)
zhengqinxu 2007-01-05
  • 打赏
  • 举报
回复
参考
declare @sql varchar(4000)
set @sql = 'select Name'
select @sql = @sql + ',sum(case Subject when '''+Subject+''' then Result end) ['+Subject+']'
from (select distinct Subject from CJ) as a
select @sql = @sql+' from test group by name'
exec(@sql)
rookie_one 2007-01-05
  • 打赏
  • 举报
回复
case ....when.....then...
mengmou 2007-01-05
  • 打赏
  • 举报
回复
搜“行转列”
子陌红尘 2007-01-05
  • 打赏
  • 举报
回复
用交叉表查询。

27,580

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧