如果我想知道每個用戶,他們花了多少時間在Intranet的某一天,我可以使用自定義功能 - 2個例子:如何迭代填充臨時表並將結果填充到列?
select * from [dbo].[usertime]('2016-04-08')
userid totaltime
-----------------
1 4430
2 11043
5 13045
select * from [dbo].[usertime]('2016-04-09')
userid totaltime
-----------------
1 345
3 12066
9 15344
我在功能無法控制,只能使用它的輸出。 totaltime
在幾秒鐘內。
從另一個表,我可以在一年中選擇日期:
select * from dates;
date
----------
2016-01-01
...
2016-04-08
2016-04-09
我想在dates
表運行自定義功能usertime
每個date
和結果存儲在一個臨時表中,如下:
userid 2016-01-01 .. 2016-04-08 2016-04-09
----------------------------------------------
1 .. 4430 345
2 .. 11043 0
3 .. 0 12066
5 .. 13045 0
9 .. 0 15344
這就要求我打電話給在循環usertime
,僞:
create table #usertime
(
userid int
date date
seconds int
)
select * into #dates from dates;
foreach (#dates as _date)
update #usertime with [dbo].[usertime](_date)
select * from #usertime
userid 2016-01-01 .. 2016-04-08 2016-04-09
----------------------------------------------
1 .. 4430 345
2 .. 11043 0
3 .. 0 12066
5 .. 13045 0
9 .. 0 15344
我知道我需要動態SQL,每次循環使用不同的日期,並且stuff()
可以根據來自#usertime
的結果集中的行創建多個列。但我不明白如何使用這些功能。任何人都可以幫助我嗎?
可能出現[SQL Server動態PIVOT查詢?]的重複(http://stackoverflow.com/questions/10404348/sql-server-dynamic-pivot-query)。這已被問及答覆數百次和數百次。 –
[dbo]。[usertime]('2016-04-08')必須收到userid。不是嗎? –
@RuslanK。 - 不,它不能。唯一的輸入是日期。該函數檢索當天首先登錄的用戶的不同列表,然後從另一個表中檢索在該網站上花費的總時間:) – Pr0no