我有2个表,客户和销售
我需要从Sales中提取尚未加载到Customers表中的所有客户,并且在我被要求添加2个MAX()
字段之前,我构建了以下查询,该查询运行良好。
以下是查询:
INSERT INTO Customers (.....)
SELECT distinct
d.UserName,
d.postalCode,
d.location,
d.country,
max(d.invoiceamount) invoiceamount,
max(d.itemscount) itemscount,
d.storeID
FROM S.dbo.[Sales] d
LEFT JOIN G.dbo.Customers s ON d.Username=s.UserName
WHERE s.UserName IS NULL
AND d.username IS NOT NULL
GROUP BY d.UserName, d.postalCode, d.location,
d.country, max(d.invoiceamount), max(d.itemscount), d.storeID
但查询不接受分组中的max():
在另一种情况下,我使用CROSS APPLY
但是从这里开始我必须提取一个表中Username为NULL的记录...我不知道如何构建查询。
答案 0 :(得分:2)
您不需要max()
中的group by
:
INSERT INTO Customers (.....)
SELECT d.UserName, d.postalCode, d.location, d.country,
max(d.invoiceamount) invoiceamount,
max(d.itemscount) itemscount,
d.storeID
FROM S.dbo.[Sales] d LEFT JOIN
G.dbo.Customers s
ON d.Username = s.UserName
WHERE s.UserName IS NULL AND d.username IS NOT NULL
GROUP BY d.UserName, d.postalCode, d.location, d.country, d.storeID;
所有非聚合列都应位于group by
。