如何编写正确的查询?

时间:2018-01-04 11:00:16

标签: sql sql-server tsql

Select Amount from Encashment

我可以在两次兑现中获得金额。({{1}}) 但是,我希望从每个兑换的MoneyAccepted获得金额 例如:兑现发生在20-10-2017,直到这个日期时间被接受为101(100(2017-10-16 12:36:30.081)+1(2017-10-15 09:36:40.057))钱。
我怎么能得到它?

提前致谢!

2 个答案:

答案 0 :(得分:2)

我认为你在寻找的是:

DECLARE @Encashment AS TABLE (MachineID INT, Amount INT, Occured DATETIME2)
DECLARE @MoneyAccepted AS TABLE (MachineID INT, Amount INT, Occured DATETIME2)

INSERT @Encashment (MachineID, Amount, Occured)
VALUES  (1, 101, '20171020 09:36:40.057')
,       (1, 203, '20171014 12:36:30.081')
,       (1, 400, '20171011 04:17:38.023')

INSERT @MoneyAccepted (MachineID, Amount, Occured)
VALUES  (1, 1, '20171015 09:36:40.057')
,       (1, 100, '20171016 12:36:30.081')
,       (1, 100, '20171012 16:17:38.023') 
,       (1, 100, '20171014 09:17:38.023')
,       (1, 1, '20171013 09:37:47.057')
,       (1, 1, '20171013 09:37:47.057')
,       (1, 1, '20171012 15:37:31.081') 

SELECT      E.Occured AS Encashment_Occured
,           SUM(MA.Amount) AS SUM_Amount
FROM        @MoneyAccepted AS MA
INNER JOIN (
                SELECT  MachineID
                ,       Amount
                ,       Occured
                ,       LAG(Occured) OVER(PARTITION BY MachineID ORDER BY Occured) AS Previous_Occured 
                FROM    @Encashment
            ) AS E
        ON  E.MachineID = MA.MachineID
        AND E.Occured > MA.Occured
        AND E.Previous_Occured <= MA.Occured
GROUP BY    E.Occured

结果:

+-----------------------------+------------+
|     Encashment_Occured      | SUM_Amount |
+-----------------------------+------------+
| 2017-10-14 12:36:30.0810000 |        203 |
| 2017-10-20 09:36:40.0570000 |        101 |
+-----------------------------+------------+

这使用了在SQL Server 2012中引入的LAG,以便在一行中获取适用日期的范围。

答案 1 :(得分:1)

请编辑您的问题,删除html并使用纯文本作为样本数据。

我认为你可以使用CROSS APPLY。 试试这个:

WITH Encashment AS (
    SELECT  T.MachineId, T.Amount, CAST(Occured AS DATETIME) AS Occured
    FROM (VALUES 
          (1, 101, '2017-10-20 09:36:40.057')
         ,(1, 203, '2017-10-14 12:36:30.081')
         ,(1, 400, '2017-10-11 04:17:38.023')
         ) AS T(MachineId, Amount, Occured)
), MoneyAccepted  AS (
    SELECT  T.MachineId, T.Amount, CAST(Occured AS DATETIME) AS Occured
    FROM (VALUES 
          (1, 1, '2017-10-15 09:36:40.057')
         ,(1, 100, '2017-10-16 12:36:30.081')
         ,(1, 100, '2017-10-12 16:17:38.023')
         ,(1, 1, '2017-10-13 09:37:47.057')
         ,(1, 1, '2017-10-13 09:37:47.057')
         ,(1, 1, '2017-10-12 15:37:47.057')
         ,(1, 100, '2017-09-15 12:37:31.081')
         ,(1, 100, '2017-09-15 16:37:31.081')
         ,(1, 100, '2017-09-16 13:37:31.081')
         ,(1, 100, '2017-09-17 13:37:31.081')
         ) AS T(MachineId, Amount, Occured)
)
SELECT M.*, EN.* 
FROM MoneyAccepted AS M
CROSS APPLY (
    SELECT TOP (1) E.* FROM Encashment AS E
    WHERE E.MachineId = M.MachineId AND E.Occured > M.Occured
    ORDER BY E.Occured ASC
) AS EN