基于sum的SQL查询

时间:2011-03-21 23:27:27

标签: sql

我有一个简单的表,其中包含我希望根据这些值的总和(最多为某个限制组总和)将块/分区分成不同的组的值。

如,。想象一下如下表:

Key   Value
-----------
A         1
B         4
C         2
D         2
E         5
F         1

我想分组,这样任何一个分组的总和都不会超过某个给定值(比如5)。

结果如下:

Group  Key    Value
-------------------
1      A          1     
       B          4
           --------  
           Total: 5     

2      C          2
       D          2
           --------
           Total: 4

3      E          5
           --------
           Total: 5

4      F          1
           --------
           Total: 1

这样的查询可能吗?

2 个答案:

答案 0 :(得分:2)

虽然我倾向于同意这些最好在SQL之外完成的评论,但这里有一些SQL似乎大致与你所要求的一致:

with mytable AS (
    select 'A' AS [Key], 1 AS [Value] UNION ALL
    select 'B', 4 UNION ALL
    select 'C', 2 UNION ALL
    select 'D', 2 UNION ALL
    select 'E', 5 UNION ALL
    select 'F', 1
)
, Sums AS (
    select T1.[Key] AS T1K
        , T2.[Key] AS T2K
        , (SELECT SUM([Value])
           FROM mytable T3
           WHERE T3.[Key] <= T2.[Key]
           AND T3.[Key] >= T1.[Key]) AS TheSum
    from mytable T1
    inner join mytable T2
        on T2.[Key] >= T1.[Key]
)
select S1.T1K AS StartKey
    , S1.T2K AS EndKey
    , S1.TheSum
from Sums S1
left join Sums S2
    on (S1.T1K >= S2.T1K and S1.T2K <= S2.T2K)
    and S2.TheSum > S1.TheSum
    and S2.TheSum <= 5
where S1.TheSum <= 5
AND S2.T1K IS NULL

当我在SQL Server 2008上运行此代码时,我得到了以下结果:

StartKey    EndKey    Sum
A           B         5
C           D         4
E           E         5
F           F         1

从这些结果构建所需的组应该是直截了当的。

答案 1 :(得分:0)

如果您希望每组中只有两个或更少成员,则可以使用以下查询:

Select
  A.[Key] as K1 ,
  B.[Key] as K2 ,
  isnull(A.value,0) as V1 ,
  isnull(B.value,0) as V2 ,
  (A.value+B.value)as Total
from Table_1 as A left join Table_1 as B
on A.value+B.value<=5 and  A.[Key]<>B.[Key]

要查找包含更多成员的集合,您可以继续使用联接。