SQL 需要 SUM 值,然后是 2 个表的 AVG

SQL SUM Values need and then AVG of 2 Tables

由此可以得出以下结论:

   TABLE 1
   Id | final | Date
   ------------------
    1    236    02-11-14
    2     10    07-01-12
    3     58    09-02-10

   TABLE 2
   Id | final | Date
 ------------------
   1     330    02-11-14
   2     5      07-01-12
   3     100    09-02-10

同时添加 Table 1 和 Table 2 求和值(最后一列),然后从中计算出 AVG 数并将其创建为另一列平均值,然后如果 table2 例如 SUM 的原始金额(在 AVG 之前)高于 Table 1 SUM 的金额创建另一列并在该列中打印 'Tbl2 has the higher amount' 并且如果 table 1 的金额较高。

最终结果按列 table 看起来像这样:

  |tb1_final_amount|tb2_final_amount|Avg_Amount|Top_Score_tbl


   |tb1_final_amount|tb2_final_amount|Avg_Amount|Top_Score_tbl
        304              435           369.5      tb2 has highest score

这是(许多)方法之一。您可以汇总这两个表并将它们用作查询中的派生表,如下所示:

select 
    tb1_final_amount, 
    tb2_final_amount, 
    (tb1_final_amount+tb2_final_amount)/2.0 as Avg_Amount, 
    case 
       when tb1_final_amount < tb2_final_amount then 'tb2 has highest score' 
       else 'tb1 has highest score' 
    end as Top_Score_tbl 
from 
    (select SUM(final) as tb1_final_amount from TABLE1) t1, 
    (select SUM(final) as tb2_final_amount from TABLE2) t2

这样就可以了!:

--SET UP Table1
CREATE TABLE Table1 (ID INT, final INT, [Date] DATETIME)
INSERT Table1 VALUES (1, 236, '20141102')
INSERT Table1 VALUES (2,  10, '20120107')
INSERT Table1 VALUES (3,  58, '20100209')

--SET UP Table2
CREATE TABLE Table2 (ID INT, final INT, [Date] DATETIME)
INSERT Table2 VALUES (1, 330, '20141102')
INSERT Table2 VALUES (2,   5, '20120107')
INSERT Table2 VALUES (3, 100, '20100209')

-- Query
SELECT
  SUM(CASE WHEN t.TableName = 'Table1' THEN T.final
           ELSE 0
      END) AS tb1_final_amount,
  SUM(CASE WHEN t.TableName = 'Table2' THEN T.final
           ELSE 0
      END) AS tb2_final_amount,
  AVG(T.final) AS Avg_Amount,
  ISNULL((
          SELECT
            'Table1'
          FROM
            Table1 T1
          WHERE
            SUM(CASE WHEN t.TableName = 'Table1' THEN T.final
                     ELSE 0
                END) > SUM(CASE WHEN t.TableName = 'Table2' THEN T.final
                                ELSE 0
                           END)
         ), 'Table2')
FROM
  (
   SELECT
    'Table1' AS TableName,
    final
   FROM
    Table1
   UNION ALL
   SELECT
    'Table2',
    final
   FROM
    Table2
  ) AS T