您可以将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);