gpt4 book ai didi

sql - 如何调用用户定义函数来与 select、group by、order by 一起使用?

转载 作者:行者123 更新时间:2023-12-02 09:28:33 25 4
gpt4 key购买 nike

我有 Table1,我需要让它看起来像 Table2:

表1

VisitingCount |  Date
-----------------------
1 | 15:09
3 | 15:10
7 | 15:15
1 | 15:39
2 | 15:40
3 | 15:47

表2

VisitingCount |  Date
-----------------------------
11 | 15:00-15:30
6 | 15:30-16:00


我写了一个这样的sql用户定义函数:

create FUNCTION [dbo].[fn_GetActivityLogsArranger] (@time AS nvarchar(max))
RETURNS nvarchar(max)
AS
BEGIN
declare @Return varchar(30)

select @Return =
case
when @time between '15:00' and '15:30' then '15:00-15:30'
when @time between '15:30' and '16:00' then '15:30-16:00'
when @time between '16:00' and '16:30' then '16:00-16:30'
when @time between '16:00' and '16:30' then '16:00-16:30'
when @time between '16:30' and '17:00' then '16:30-17:00'
when @time between '17:00' and '17:30' then '17:00-17:30'
when @time between '17:30' and '18:00' then '17:30-18:00'
else 'Unknown'
end

return @Return
end

在我的sql查询中调用UDF时,我得到了正确的结果:

select 
Count(Page) as VisitingCount,
dbo.fn_GetActivityLogsArranger(CONVERT(VARCHAR(5),Date, 108))
as [Time]
from
scr_SecuristLog
where
Date between '2009-04-30' and '2009-05-02' AND
[user] in
(
select USERNAME
from scr_CustomerAuthorities
where customerID = Convert(varchar,4) and ID = Convert(varchar,43)
)
group by
dbo.fn_GetActivityLogsArranger(CONVERT(VARCHAR(5),Date, 108))
order by
dbo.fn_GetActivityLogsArranger(CONVERT(VARCHAR(5),Date, 108)) asc

但我不喜欢这种方法;我梦想的代码如下所示:

select 
Count(Page) as VisitingCount,
dbo.fn_GetActivityLogsArranger(CONVERT(VARCHAR(5),Date, 108))
as <strong>[TIME]</strong>
from
scr_SecuristLog
where
Date between '2009-04-30' and '2009-05-02' and
user] in
(
select USERNAME
from scr_CustomerAuthorities
where customerID = Convert(varchar,4) and ID = Convert(varchar,43)
)
group by <strong>[TIME]</strong>
order by <strong>[TIME]</strong> asc

最佳答案

您可以像 View 一样加入表并在那里调用您的函数。这样您就可以从 View 中的列上调用分组依据和排序依据。

select
Count(Page) as VisitingCount,
[Time]
from
(
SELECT
Page,
Date,
[user],
dbo.fn_GetActivityLogsArranger(CONVERT(VARCHAR(5),Date, 108)) as [Time]
FROM
scr_SecuristLog
) scr_SecuristLog2
where
Date between '2009-04-30' and '2009-05-02'
and
[user] in
(
select
USERNAME
from
scr_CustomerAuthorities
where
customerID=Convert(varchar,4)
and
ID=Convert(varchar,43)
)
group by
[Time]
order by
[Time] asc

关于sql - 如何调用用户定义函数来与 select、group by、order by 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/829089/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com