我尝试运行此查询,因为我正在使用Sum函数分别获取指定客户的发票。
当我尝试运行查询时,出现以下错误。
选择列表中的“ ConsumerMST_LKO.CustomerName”列无效 因为它既不包含在聚合函数中,也不包含在 GROUP BY子句。
SELECT c.customerid,
c.customername,
totalamt,
Sum(invoice.totalamt) AS total,
invoice.invoiceno,
invoice.invoicedate,
invoice.invoicemonth,
invoice.totalamt
FROM consumermst_lko AS c
RIGHT OUTER JOIN invoicedetails AS invoice
ON c.customerid = invoice.customerid
WHERE c.customerid='LKO00028153'
GROUP BY c.customerid FOR json auto
答案 0 :(得分:0)
该列必须出现在FROM
语句的SELECT
子句中,但不需要出现在SELECT列表中。
您可以在the documentation中进一步了解条款GROUP BY
中的有效表达式:
SELECT c.customerid,
c.customername,
totalamt,
.
.
.
FROM consumermst_lko AS c
RIGHT OUTER JOIN invoicedetails AS invoice
ON c.customerid = invoice.customerid
WHERE c.customerid='LKO00028153'
GROUP BY c.customerid
, c.customername,...
答案 1 :(得分:0)
要获得运行总计,常规的聚合函数将无法自行运行。最简单的方法是使用Windowing函数。
SUM
函数后面的子句告诉引擎计算总和,然后按customerid
划分(分解)并按invoicedate
进行排序。如果没有样本数据,我不确定这是否正确,但是如果您在系统上试用它,那么应该可以找到所需的内容。
SELECT
c.customerid,
c.customername,
totalamt, --<--This should be qualified with a table alias. Redundant?
SUM(i.totalamt) OVER (PARTITION BY c.customerid ORDER BY i.invoicedate) AS total,
i.invoiceno,
i.invoicedate,
i.invoicemonth,
i.totalamt
FROM consumermst_lko AS c
RIGHT OUTER JOIN invoicedetails AS i
ON c.customerid = i.customerid
WHERE c.customerid='LKO00028153' FOR JSON AUTO