SQL MERGE使用GROUP BY

时间:2012-12-14 14:16:43

标签: sql sql-server sql-server-2008

我必须做一个MERGE语句但在我需要准备查询之前,这个查询有group by一些字符​​串列和值,因为我正在做一个组,我可以不包括主键。如果我无法提供主键,怎么办MERGE

这是查询

SELECT Account,
       BillDate, 
       Name,
       SUM(ChargeAmount) AS ChargeAmount, 
       SUM(ChargeTaxes) AS ChargeTaxes,       
  FROM MyTempTable
 GROUP BY Account, BillDate, Name

现在我需要从该查询开始在我的表中执行MERGE,但我没有pk。

1 个答案:

答案 0 :(得分:7)

您可以将GROUP BY子句与MERGE一起使用。正如文件规定:

[ WITH <common_table_expression> [,...n] ]
MERGE 
    [ TOP ( expression ) [ PERCENT ] ] 
    [ INTO ] <target_table> [ WITH ( <merge_hint> ) ] [ [ AS ] table_alias ]
    USING <table_source> 
    ON <merge_search_condition>
    [ WHEN MATCHED [ AND <clause_search_condition> ]
        THEN <merge_matched> ] [...n ]
    [ WHEN NOT MATCHED [ BY TARGET ] [ AND <clause_search_condition> ]
        THEN <merge_not_matched> ]
    [ WHEN NOT MATCHED BY SOURCE [ AND <clause_search_condition> ]
        THEN <merge_matched> ] [...n ]
    [ <output_clause> ]
    [ OPTION ( <query_hint> [ ,...n ] ) ]    
;

table_source可以是:

<table_source> ::= 
{
    table_or_view_name [ [ AS ] table_alias ] [ <tablesample_clause> ] 
        [ WITH ( table_hint [ [ , ]...n ] ) ] 
  | rowset_function [ [ AS ] table_alias ] 
        [ ( bulk_column_alias [ ,...n ] ) ] 
  | user_defined_function [ [ AS ] table_alias ]
  | OPENXML <openxml_clause> 
  | derived_table [ AS ] table_alias [ ( column_alias [ ,...n ] ) ] 
  | <joined_table> 
  | <pivoted_table> 
  | <unpivoted_table> 
}

因此,您可以按照您在问题中的方式设置GROUP BY子句,如下所示:

MERGE INTO table2 AS TGT
USING
(
  SELECT Account,
       BillDate, 
       Name,
       SUM(ChargeAmount) AS ChargeAmount, 
       SUM(ChargeTaxes) AS ChargeTaxes
  FROM table1
 GROUP BY Account, BillDate, Name
) AS SRC
  ON  SRC.Account = TGT.Account AND
      SRC.Name = TGT.Name
WHEN NOT MATCHED THEN
  INSERT (Account, BillDate, Name, ChargeAmount, ChargeTaxes)
  VALUES (SRC.Account, SRC.BillDate, 
          SRC.Name, SRC.ChargeAmount, SRC.ChargeTaxes);

SQL Fiddle Demo