且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

基于具有不相关表的行值的SQL子查询

更新时间:2023-02-09 21:58:46

按照@Dominique的建议,我创建了一个自定义标量函数(使用SSMS中的向导),我将默认值用于日期,就像从播放开始一样与存储过程,这使得测试更加容易.这个问题需要一个函数,因为它将每行返回一个值,而存储过程则不会.

Following the suggestion by @Dominique I created a custom scalar function (using the wizard in SSMS), I used default values for the dates as I had started by playing with stored procedure and that made it easier to test. This problem requires a function as it will return a value per row, where a stored procedure will not.

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      James Jenkins
-- Create date: September 2015
-- Description: Counts Business Days for UPMC during a span of dates
-- =============================================
CREATE FUNCTION dbo.UPMCBusinessDayCount 
(
    -- Add the parameters for the function here
    @StartDate date = '2015-08-01',
    @EndDate date = '2015-08-31'
)
RETURNS int
AS
BEGIN
    -- Declare the return variable here
    DECLARE @BusDay int

    -- Add the T-SQL statements to compute the return value here
    SELECT @BusDay = Count(UPMCCALENDARM1.DATE) 
        from dbo.UPMCCALENDARM1
        where UPMC_BUSINESS_DAY = 't'
        and UPMCCALENDARM1.DATE between @StartDate and @EndDate

    -- Return the result of the function
    RETURN @BusDay

END
GO

在数据库中创建函数之后,我将这两行添加到我的select语句中,并且运行良好.

After the function is created in the database I added these two lines to my select statement, and it works perfectly.

--Custom function counts business days on UPMCCALENDARM1
, dbo.UPMCBusinessDayCount(DV_im_Audit_ASSIGNMENT.Time, Detail.RESOLVED_TIME) as BusDay

我可以将此函数用于其中具有日期数据(或数据库中的任何查询)的任何范围.我可能会删除默认日期,并添加第三个参数以计算非工作日(UPMC_BUSINESS_DAY ='f').但问题就解决了.

I can use this function for any span that has date data in this (or any query on the database). I will probably be removing the default dates as well as adding a third parameter to count non-business days (UPMC_BUSINESS_DAY = 'f'). But as it is the problem is solved.