日期:2014-05-17 浏览次数:20674 次
declare @sql varchar(8000)
set @sql='select formid '
select @sql=@sql+',max(case foodid when '+ ltrim(foodid) +'
then foodnumber else 0 end) as ['+ltrim(foodname)+']'
from (select distinct foodname,foodid from tb_GA_OrderMeal as a
left outer join tb_GA_MealType as b on a.foodid = b.id)as c
set @sql=@sql+' from tb_GA_OrderMeal group by formid'
exec(@sql)
----------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-10-10 13:40:23
-- Version:
-- Microsoft SQL Server 2014 (CTP1) - 11.0.9120.5 (X64)
-- Jun 10 2013 20:09:10
-- Copyright (c) Microsoft Corporation
-- Enterprise Evaluation Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: ) (Hypervisor)
--
----------------------------
--> 测试数据:[tb_GA_OrderMeal]
if object_id('[tb_GA_OrderMeal]') is not null drop table [tb_GA_OrderMeal]
go
create table [tb_GA_OrderMeal]([foodid] int,[foodnumber] int,[formid] int)
insert [tb_GA_OrderMeal]
select 1,20,1 union all
select 2,24,1 union all
select 3,22,1 union all
select 1,30,2 union all
select 2,31,2
--> 测试数据:[tb_GA_MealType]
if object_id('[tb_GA_MealType]') is not null drop table [tb_GA_MealType]
go
create table [tb_GA_MealType]([id] int,[foodname] varchar(4))
insert [tb_GA_MealType]
select 1,'早饭' union all
select 2,'午饭' union all
select 3,'晚饭'
--------------开始查询--------------------------
CREATE PROC test
AS
declare @sql varchar(8000)
set @sql='select formid '
select @sql=@sql+',max(case foodid when '+ ltrim(foodid) +'
then foodnumber else 0 end) as ['+ltrim(foodname)+']'
from (select distinct foodname,foodid from tb_GA_OrderMeal as a
left outer join tb_GA_MealType as b on a.foodid = b.id)as c
set @sql=@sql+' from tb_GA_OrderMeal group by formid'
exec(@sql)
EXEC test
----------------结果----------------------------
/*
formid 晚饭 午饭 早饭
----------- ----------- ----------- -----------
1&nb