我有一个包含激光表格名称和日期的表格。
我的表名为myBWB_LaserForms
laserform editwhen
LRAP1.lpw 2009-09-03 16:06:00.000
CON29R.lpw 2009-10-29 12:35:00.000
UN1.lpw 2010-03-02 11:38:00.000
UN244.lpw 2012-04-19 12:14:00.000
LT3.lpw 2013-01-02 11:00:00.000
LRAP1.lpw 2007-12-10 15:34:00.000
我想要制作的是一份报告,其左侧是激光形式的名称,而左侧是激光形式的名称,例如: 2004年,2005年,2006年,然后每个交叉单元格将计算该特定年份的表单名称的记录数。
通常我会做类似
的事情select l.laserform,
(select count(*) from mybwb_laserforms l1 where l1.laserform=l.laserform and year(editwhen)=2004) AS [2004],
(select count(*) from mybwb_laserforms l2 where l2.laserform=l.laserform and year(editwhen)=2005) AS [2005],
(select count(*) from mybwb_laserforms l3 where l3.laserform=l.laserform and year(editwhen)=2006) AS [2006],
(select count(*) from mybwb_laserforms l4 where l4.laserform=l.laserform and year(editwhen)=2007) AS [2007]
from mybwb_laserforms l
group by l.laserform
order by l.laserform
但是我意识到这是非常可怕的SQL,我应该对它更加聪明。
我一直在努力学习如何使用枢轴功能,但我正在努力探索它。
我发现的大多数示例似乎都有硬编码的查询列 - 如果枢轴可以是动态的并且获得唯一的年份(editwhen)值,那么我将不会修改查询明年和之后的一年。
答案 0 :(得分:0)
总结一下。
select laserform,
sum(case when year(editwhen)=2004 then 1 else 0 end) AS [2004],
sum(case when year(editwhen)=2005 then 1 else 0 end) AS [2005],
sum(case when year(editwhen)=2006 then 1 else 0 end) AS [2006],
sum(case when year(editwhen)=2007 then 1 else 0 end) AS [2007]
from mybwb_laserforms
where year(editwhen) between 2004 and 2007
group by laserform
order by laserform
或动态
declare @Year int = year(GetDate());
declare @Years TABLE ([year] varchar(4));
insert into @Years values (@Year-12),(@Year-11),(@Year-10),(@Year-9);
declare @SQLSums varchar(max) = '';
select @SQLSums = @SQLSums +char(13)+', sum(case when year(editwhen)='+[year]+' then 1 else 0 end) AS ['+[year]+']'
from @Years;
DECLARE @SQL nvarchar(max) = 'select laserform'+ @SQLSums +'
from mybwb_laserforms
group by laserform
where year(editwhen) between '+cast(@Year-12 as varchar)+' and '+cast(@Year-9 as varchar)+'
order by laserform';
--select @SQL;
exec (@SQL);