Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL如何计算每个日期的所有剩余值_Sql_Sql Server_Sql Function - Fatal编程技术网

SQL如何计算每个日期的所有剩余值

SQL如何计算每个日期的所有剩余值,sql,sql-server,sql-function,Sql,Sql Server,Sql Function,我有以下SQL函数 CREATE FUNCTION [dbo].[GetCardDepartRemains] ( @CardId INT, @DepartId INT, @Date DATETIME = NULL, @DocumentId INT = NULL ) RETURNS INT AS BEGIN DECLARE @Res INT SELECT @Res = ISNULL(SUM(CASE WHEN Operations

我有以下SQL函数

CREATE FUNCTION [dbo].[GetCardDepartRemains] 
(
    @CardId INT,
    @DepartId INT,
    @Date DATETIME = NULL,
    @DocumentId INT = NULL
)
RETURNS INT
AS
BEGIN
    DECLARE @Res INT

    SELECT
        @Res = ISNULL(SUM(CASE WHEN Operations.[Output] = 0 AND Operations.RecipientId = @DepartId THEN 1 ELSE -1 END), 0)
    FROM dbo.Operations
    WHERE  Operations.CardId = @CardId
        AND (Operations.[Output] = 0 AND Operations.RecipientId = @DepartId OR Operations.Input = 0 AND Operations.SenderId = @DepartId)
        AND (@Date IS NULL OR Operations.[Date] <= @Date)

    RETURN @Res
END
GO
但是这个查询的执行时间超过了2分钟,所以我们需要编写一个新的查询

我的查询可以在特定日期(例如“2016-10-04”)找到每个部门每张卡的所有剩余部分

SELECT 
    [Card],
    Depart,
    Res
FROM          
    (SELECT
        Cards.Id as [Card],
        Departments.Id as Depart,
        ISNULL(SUM(CASE WHEN Operations.[Output] = 0 AND Operations.RecipientId = Departments.Id THEN 1 ELSE -1 END), 0) as Res
    FROM Operations
    CROSS JOIN Cards
    CROSS JOIN Departments
    WHERE  Operations.CardId = Cards.Id
    AND (Operations.[Output] = 0 AND Operations.RecipientId = Departments.Id OR Operations.Input = 0 AND Operations.SenderId = Departments.Id)
    AND (Operations.[Date] <= '2016-10-04') 

    GROUP BY Cards.Id, Departments.Id
    ) as X
WHERE Res = -1

是否可以帮助重新编写此查询以查找所有日期的剩余内容?

假设SQL Server为2008或更高版本:

要查找所有日期,只需按如下方式注释掉日期筛选器:

-- AND (Operations.[Date] <= '2016-10-04') 

将-30更改为过去的天数。所以一年前应该是-364。

您使用的是哪个版本的sql server?只需将函数更改为内联函数就足够了。使用标量函数的问题在于,它会对查询中的每一行执行两次,而SQL server在逐行迭代中表现不佳。
-- AND (Operations.[Date] <= '2016-10-04') 
AND (Operations.[Date] between between getDate()-30 and getDate()