SQL Server:如何使用变量数据,临时表填充列?

时间:2018-02-15 19:04:52

标签: sql-server-2008-r2

这是基本查询,问号是我需要帮助的地方(至少)

Declare @Start datetime
Declare @End datetime

Set @Start = {mindate}
Set @End = {maxdate}

Select    
    e.id, p.date, p.pdn1?, p.hours1?, p.pdn2?, p.hours2? ... p.pdn10?, p.hours10?
from 
    e
join 
    p on e.filekey = p.filekey
where 
    p.eventdate between @start and @end

表e

uniqueid
filekey
id

表p

uniqueid
filekey
eventdate
pdn
hours

所需的输出应如下所示:

id     date     cat1     hours1     cat2    hours2   ....   cat10     hours10

我遇到的问题是有39种不同的pdn,并且在特定日期可能有多达10种。如果与该p.pdn相关的p.hours为0或不存在,则它不应出现在最终结果中。 p表包含不同行的数据,但如果p.eventdate相同,我需要将不同的行组合到同一行。谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

我认为这会做到这一点,尽管您可能想要使用RANK()或其他东西,具体取决于工作时间的方式或是否需要订购pdn。Rextester example

declare @Start datetime
declare @End datetime

set @Start = CAST(GETDATE() as DATE)
set @End = CAST(DATEADD(day,1,GETDATE()) as DATE)

;WITH CTE AS
(
    select uniqueid, pdn, hours, filekey, eventdate,
           'PDN' + CAST(ROW_NUMBER() OVER (PARTITION BY filekey ORDER BY hours) as varchar) as PDNrnk,
           'HOURS' + CAST(ROW_NUMBER() OVER (PARTITION BY filekey ORDER BY hours) as varchar) as Hoursrnk
    from p
    where hours > 0
          and eventdate >= @start and eventdate < @end
)
select  id, eventdate as date, 
        MAX([PDN1]) as CAT1,MAX([HOURS1]) as HOURS1,
        MAX([PDN2]) as CAT2,MAX([HOURS2]) as HOURS2,
        MAX([PDN3]) as CAT3,MAX([HOURS3]) as HOURS3,
        MAX([PDN4]) as CAT4,MAX([HOURS4]) as HOURS4,
        MAX([PDN5]) as CAT5,MAX([HOURS5]) as HOURS5,
        MAX([PDN6]) as CAT6,MAX([HOURS6]) as HOURS6,
        MAX([PDN7]) as CAT7,MAX([HOURS7]) as HOURS7,
        MAX([PDN8]) as CAT8,MAX([HOURS8]) as HOURS8,
        MAX([PDN9]) as CAT9,MAX([HOURS9]) as HOURS9,
        MAX([PDN10]) as CAT10,MAX([HOURS10]) as HOURS10
from 
(
    select e.id,cte.eventdate,cte.pdn,cte.Hours,cte.PDNrnk, cte.Hoursrnk
    from e
    inner join CTE
        on (e.filekey = CTE.filekey)
)q
PIVOT 
(
    MIN(Pdn)
    FOR PDNrnk in ([PDN1],[PDN2],[PDN3],[PDN4],[PDN5],[PDN6],[PDN7],[PDN8],[PDN9],[PDN10])
)as pvtPdn
PIVOT 
(
    MIN(Hours)
    FOR Hoursrnk in ([HOURS1],[HOURS2],[HOURS3],[HOURS4],[HOURS5],[HOURS6],[HOURS7],[HOURS8],[HOURS9],[HOURS10])
)as pvtHours
group by id, eventdate