列中所有可能的列组合,在SQL中为sum

时间:2016-05-23 11:42:11

标签: sql sql-server entity-framework sql-server-2008

我想生成具有多个组条件的报告,并且需要显示我的表的所有可能组合以及任何一列的总和

这是我的表结构

Company Budget  Account Benificiary Objevctive  Spare1  Spare2  Amount
C1        B1     A1       BA1          OB1         0     0       200
C1        B2     A1       BA2          OB2         0     0       300
C2        B1     A2       BA2          OB2        S1     S1      400
C1        B1     A1       BA1          OB1         0     0       400

以下是所需的输出,其中包含7列的所有可能组合,以及基于组合的最后一列中的总和

Company Budget  Account Benificiary Objevctive  Spare1   Spare2     Amount
    C1        B1      A1       BA1           OB1       0       0     600
    C1        B1      A1       BA1           OB1       0       S1    0
    C1        B1      A1       BA1           OB1       S1       0    0
    C1        B1      A1       BA1           OB1       S1      S1    0
    C1        B1      A1       BA1           OB2       0       0     0
    C1        B1      A1       BA1           OB2       0       S1    0
    C1        B1      A1       BA1           OB2       S1      0     0
    C1        B1      A1       BA1           OB2       S1      S1    0
    C1        B1      A1       BA2           OB1       0       0     0

我无法生成将提供上述输出的查询

1 个答案:

答案 0 :(得分:0)

我可以使用下面的查询

来实现上述输出
SELECT B.BENEFICIARY,
       B.BUDGETHOLDER,
       B.CITY,
       B.FIELDNAME,
       B.OBJECTIVE,
       SUM(B.value)
FROM (
    SELECT DISTINCT A.BENEFICIARY,
                    A.BUDGETHOLDER,
                    A.CITY,
                    A.FIELDNAME,
                    A.OBJECTIVE,
                    A.value
    FROM (
        SELECT t.BENEFICIARY,
               t.BUDGETHOLDER,
               t.CITY,
               t.FIELDNAME,
               t.OBJECTIVE,
               t.value value
        FROM #temp T, #temp TT
    ) A
    LEFT JOIN #temp T1 ON A.BENEFICIARY = t1.BENEFICIARY
        AND A.BUDGETHOLDER = t1.BUDGETHOLDER
        AND A.CITY = t1.CITY
        AND A.OBJECTIVE = t1.OBJECTIVE
) B
GROUP BY B.BENEFICIARY,
         B.BUDGETHOLDER,
         B.CITY,
         B.OBJECTIVE,
         B.FIELDNAME