0

我使用 SQL Server 2012,我有这些表:

Tb1 ( ID Int, CodeID Int, Value Int)

 ID     CodeID    Value
 ----------------------
 1      1         10
 2      1         14
 3      1         5
 4      1         25
 5      2         12
 6      2         17
 7      2         4
 8      2         10
 9      2         6

Tb2 ( CodeID Int Value Int)

CodeID    Value
---------------
1         25
2         20

我想要查询从 Tb1 获取 SUM(Tb1.Value) <= Tb2.Value 的记录

例如上述记录的结果是:

Tb1.ID   Tb1.CodeID  Tb1.Value   UsedValue     Tb2.Value
--------------------------------------------------------
1         1          10          10            25
2         1          14          14            25
3         1          5           1             25
5         2          12          12            20
6         2          17          8             20

我使用游标来获取上述查询。但是我的查询以低性能执行。我想要一个没有光标的查询。

编辑 1 UsedValue 是 Tb1.Value,直到 Tb1.Value 的总和低于 Tb2.Value。

4

3 回答 3

0
select 
T.Id
, T.CodeId
, T.Value
, T.Value -(Total - T2.Value) as UsedValue
, T2.Value as T2_Value
from 
(
   select a.id
   , a.codeid
   , a.Value
   , sum(b.value) as Total
   from Tb1 a join Tb1 b 
   on a.Id >= b.id and a.CodeId = b.CodeId
   group by a.id, a.CodeId, a.Value
) T
join Tb2 T2 
on T.CodeId = T2.CodeId
where Total < (T2.Value + T.Value)

我写这段代码时只有一个假设。这些行是按 ID 排序的,如果不是真的,你必须添加排序列!

于 2013-01-20T11:16:55.533 回答
0
select id,codeid,value,case when vt>0 then value else value+vt end usedvalue, 
       value2 
from (select *, value2-runtot vt,
       max(case when value2-runtot<0 then value2-runtot else -runtot end) 
       over(PARTITION BY codeid)  usedvalue 
           from (SELECT t1.id, t1.codeid, t1.value, t2.value value2, 
                sum(t1.value) OVER(PARTITION BY t1.codeid ORDER BY t1.id) runtot
              FROM tb1 t1
              INNER JOIN tb2 t2 ON t1.codeid = t2.codeid
              ) X
             )Y
where vt>=usedvalue
于 2013-01-21T07:15:27.670 回答
0

尝试这个:

;WITH Subtotals
AS
(
  SELECT
    T1.Id, T1.CodeId, SUM(T2.Value) SubTotal  
  FROM Tb1 T1
    JOIN Tb1 T2
       ON T1.CodeId = T2.CodeId
         AND T1.Id >= T2.Id
  GROUP BY T1.Id, T1.CodeId
)
SELECT
    S.ID,
    S.CodeID,
    T1.Value,
    CASE WHEN T2.value >= S.Subtotal
         THEN T1.value
         ELSE T1.value - (S.Subtotal - T2.value)
    END UsedValue,
    T2.Value T2Value
FROM Subtotals S
   JOIN Tb2 T2
      ON S.CodeId = T2.CodeId
   JOIN Tb1 T1
      ON S.Id = T1.Id
WHERE T2.Value >= S.SubTotal - T1.Value

查看SQL FIDDLE上的结果

于 2013-01-20T08:56:59.353 回答