我有一个c#网页,我正在使用SQL作为数据库
我需要将表中的数据显示为gridview
SQL:我有一个表格如下
Exec_Date Plat Pass Fail
----------------------------------------------------------------
2017-02-19 12:32:43.570 MSSQL 10 12
2017-02-19 12:32:43.570 MSSQL 10 12
2017-02-18 12:32:43.570 Sybase 10 12
2017-02-18 12:32:43.570 Oracle 10 12
我想将表格转换为演示文稿的自定义格式
Status 18/02 19/02
-------------------------
Pass 20 20
Fail 24 24
以上可能由Pivot完成吗?如果是这样,任何人都可以提出一些想法吗?
到目前为止,我已经尝试了以下内容,而@Names没有解析查询中的变量值
create table #TempTable
(Exec_Date varchar(max),
Pass int,
Ref_Status varchar(max)
)
Insert into #TempTable
select cast(Exec_Date as DATE) as Date,SUM(Pass) as Pass,'PASS' from F_Exec where cast(Exec_Date as DATE) >= '2017-02-17' and cast(Exec_Date as DATE) <= '2017-02-20' group by Exec_Date,Pass
DECLARE @Names varchar(max)
SELECT @Names = COALESCE(@Names + '],[', '[') + Exec_Date FROM #TempTable
select @Names=@Names+']'
Select * from #TempTable pivot
(SUM(Pass) for Exec_Date IN (@Names) )as PivotTable
变量@Names不被视为变量。如果我从变量中手动替换结果值
答案 0 :(得分:1)
试试这段代码:
declare @tbl table (Exec_Date datetime, Plat varchar(max), Pass int, Fail int)
insert into @tbl(Exec_Date , Plat , Pass , Fail ) values
('2017-02-19 12:32:43.570', 'MSSQL',10,12),
('2017-02-19 12:32:43.570', 'MSSQL',10,12),
('2017-02-18 12:32:43.570', 'Sybase',10,12),
('2017-02-18 12:32:43.570', 'Oracle',10,12)
select * from
(
select Date,Status,sum(Success) success from
(
select left(convert(varchar(20),Exec_Date,103),5) as [Date],Pass,Fail from @tbl
) as baseData
unpivot
(
Success for Status in (Pass,Fail)
) as tblUnPivot
group by date ,status
) as baseData
pivot
(
sum(success)
for Date in ([18/02],[19/02])
) as tblPivot
order by Status
答案 1 :(得分:1)
我得到了解决方案
声明了nvarchar变量并连接了查询&amp;动态列名称
DECLARE @sqlstring nvarchar(MAX)
SET @sqlstring =N'
Select * from #TempTable pivot (SUM(Pass) for Exec_Date IN (' +@Names+') )as PivotTable;';
EXEC sp_executesql @sqlstring;