日期:2014-05-18  浏览次数:20679 次

一次查询多条合并到一条记录的问题
我有两个表,结构大致如下:

A表

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


如上所示,每组数据要包含8种数据指标,但是在数据库里为8条记录,能不能通过SQL将A表中的内容合成一条记录,分别赋予它不同的字段名称。

------解决方案--------------------
用交叉表查询。
------解决方案--------------------
搜“行转列”
------解决方案--------------------
case ....when.....then...
------解决方案--------------------
参考
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)
------解决方案--------------------
--這樣?
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)