T-SQL动态查询和透视

时间:2015-02-11 10:22:37

标签: sql-server tsql

我有数据显示人们在月中更改了角色,并希望在新的开始日期之后计算活动。我可以将表的结果用作动态查询,我有一个返回以下结果集的查询: -

Firstname    Surname    StartDate
----------------------------------
Jon          Smith      2015-01-01
Paul         Jones      2014-07-23
...

因此查询看起来像:

SELECT Firstname +' '+ surname, month,  count(1) FROM dataTable
WHERE (Firstname='John' AND Surname='Smith' AND date >=2015-01-01)
OR (Firstname='Paul' AND Surname='Jones' AND date >=2014-07-23)
OR ...

但'OR'的数量取决于第一个表中的行数

Name        Month   Count
----------------------------------
Jon Smith   1       15
Paul Jones  1       16
Jon Smith   2       30
Paul Jones  2       25
Charlie Gu  1       52 

然后我可以转向

Name          1      2
--------------------------
Jon Smith     15     30
Paul Jones    16     25
Charlie Gu    52     NULL

提前致谢

2 个答案:

答案 0 :(得分:1)

在我看来,Ako是正确的,简单的连接应该是技巧而不是动态查询。

declare @NewStartDates table
    (
     Firstname nvarchar(100),
     Surname nvarchar(100),
     StartDate date
    );

insert  into @NewStartDates
        (Firstname, Surname, StartDate)
values  (N'Jon', N'Smith', '20150101'),
        (N'Paul', N'Jones', '20140723');

select  d.Firstname,
        d.Surname,
        year(d.Date) * 100 + month(d.Date) as Period,
        count(*) as ActivityCount
from    dataTable as d
inner join @NewStartDates as n
        on d.Firstname = n.Firstname
           and d.Surname = n.Surname
           and d.Date >= n.StartDate
group by d.Firstname,
        d.Surname,
        year(d.Date) * 100 + month(d.Date);

答案 1 :(得分:0)

请参阅此内容 - 它会让您完全了解如何获取动态列查询。Dynamic Column Generation - Pivot [SQL]