SQL如何计算每个日期的所有遗骸

时间:2017-03-18 15:10:13

标签: 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.[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

在特定日期某些部门的某些产品仍然有效。

如果它小于零则表示数据库存在问题

现在我需要找到每张卡片的所有遗骸,每个部门都会找到结果错误的数据库中的所有日期。

从理论上讲,我们可以通过在类似

的查询中调用此过程来解决这个问题
SELECT DISTINCT Operations.[Date] as [Date],
        Departments.Id as Depart,
        Cards.Id as [Card],
        [dbo].[GetCardDepartRemains] (Cards.Id, Departments.Id,Operations.[Date],NULL) as Res

FROM [jewellery].[dbo].[Cards] 
    CROSS JOIN [jewellery].[dbo].[Departments] 
    CROSS JOIN [jewellery].[dbo].[Operations]
WHERE [dbo].[GetCardDepartRemains] (Cards.Id, Departments.Id,Operations.[Date],NULL) = -1  

但是这个查询执行的时间超过2分钟,所以我们需要编写一个新的查询。

我的查询可以查找特定日期每个部门的每张卡的所有遗骸(例如,&#39; 2016-10-04&#39;)

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

您能否帮助重新编写此查询以查找所有日期的遗骸?

1 个答案:

答案 0 :(得分:1)

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

要查找所有日期,只需注释掉日期过滤器,如下所示:

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

如果您需要过滤日期范围:

AND (Operations.[Date] between between getDate()-30 and getDate()

将-30改为过去多少天。所以一年前会是-364。