7

我必须做一个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。

4

1 回答 1

10

您可以将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 小提琴演示

于 2012-12-14T14:38:37.227 回答