SQL如何将一个表里的不同条件查询结果拼接显示

如下所示:
数据库图如下:

我要根据她的销售价格,来得出如下的表格

请问通过SQL语句 可以实现么?

关系型数据库是以一行来表示一条数据的,而不是一列。你要得出的那个表格,一行没有任何意义。

代码仅作参考:

declare @count0 int;
declare @count1 int;
declare @count2 int;
declare @count3 int;

if(object_id('TableA') is not null) drop table TableA
select getdate() as createTime, 产品名称 into TableA from [表名] where 销售金额 >=200 and 销售金额 <= 599;

if(object_id('TableB') is not null) drop table TableB
select getdate() as createTime, 产品名称 into TableB from [表名] where 销售金额 >=600 and 销售金额 <= 899;

if(object_id('TableC') is not null) drop table TableC
select getdate() as createTime, 产品名称 into TableC from [表名] where 销售金额 >=900 ;

select @count1 = count(1) from TableA;
select @count2= count(1) from TableB;
select @count3= count(1) from TableC;

set @count0 = @count1;
if @count0<@count2
begin
set @count0 = @count2;
end

if @count0<@count3
begin
set @count0 = @count3;
end

declare @i int;
set @i = 0;
while(@count1+@i)<@count0
begin
    insert into TableA values(getdate(),'');
    set @i = @i+1;
end

SET @i=0;
while(@count2+@i)<@count0
begin
    insert into TableB values(getdate(),'');
    set @i = @i+1;
end

SET @i=0;
while(@count3+@i)<@count0
begin
    insert into TableC values(getdate(),'');
    set @i = @i+1;
end

select a.产品名称 as '200到599',b.产品名称 as '600到899',c.产品名称 as '900以上'
from (select row_number() over(order by createTime) as rownum, 产品名称 from TableA) a
left join
(select row_number() over(order by createTime) as rownum, 产品名称 from TableB) b on a.rownum = b.rownum
left join
(select row_number() over(order by createTime) as rownum, 产品名称 from TableC) c on c.rownum = b.rownum

温馨提示:内容为网友见解,仅供参考
第1个回答  2014-06-12
select max(case when 销售金额 between 200 and 599 then 产品名称 else null end) 价格200到599,
max(case when 销售金额 between 600 and 899 then 产品名称 else null end) 价格600到899,
max(case when 销售金额 > 900 then 产品名称 else null end) 价格900以上
from 表名 ;本回答被网友采纳
第2个回答  2014-06-12
用 and 和 or 一起实现
相似回答