我在计算分组查询中的ID时遇到问题。问题是该查询是根据另一个变量分组的。例如,我需要计算发票内订购的产品数量,而此发票在公司内部,可以生成多个发票。我希望它很清楚;无论如何,我希望这个SQL能够更加清晰:
SELECT C.FULLNAME,C.COMPANY_ID,SUM(I.GROSSTOTAL) AS TOTAL,
SUM(I.OTHER_MONEY_VALUE/1.18) AS OTHER_TOTAL,
COUNT(IR.PRODUCT_ID) AS NO_PRODUCTS
FROM COMPANY C
JOIN #DSN2_ALIAS#.INVOICE I ON C.COMPANY_ID=I.COMPANY_ID
JOIN #DSN2_ALIAS#.INVOICE_ROW IR ON I.INVOICE_ID=IR.INVOICE_ID
JOIN #DSN3_ALIAS#.PRODUCT P ON P.PRODUCT_ID=IR.PRODUCT_ID
JOIN #DSN3_ALIAS#.PRODUCT_CAT PC ON P.PRODUCT_CATID=PC.PRODUCT_CATID
WHERE P.PRODUCT_ID=<cfqueryparam value="#attributes.product_id#" cfsqltype="cf_sql_integer">
GROUP BY C.COMPANY_ID,C.FULLNAME
ORDER BY TOTAL DESC
在我定义产品ID之后,查询在输出中列出公司列表及其总销售额,并且NO_PRODUCTS与发票数量具有相同的值,因为查询按company_id和fullname分组它,但每个发票里面有多个产品,因此变量no_products被错误定义:(
如何才能正确计算?
答案 0 :(得分:0)
您可以尝试执行内部查询。使用发票检索产品计数。类似的东西。
SELECT C.FULLNAME,C.COMPANY_ID,SUM(I.GROSSTOTAL) AS TOTAL,
SUM(I.OTHER_MONEY_VALUE/1.18) AS OTHER_TOTAL,NO_PRODUCTS
FROM COMPANY C
JOIN #DSN2_ALIAS#.INVOICE I ON C.COMPANY_ID=I.COMPANY_ID
JOIN (select INVOICE_ID,count(PRODUCT_ID) as NO_PRODUCT from #DSN2_ALIAS#.INVOICE_ROW group by invoice_id) IR ON I.INVOICE_ID=IR.INVOICE_ID
JOIN #DSN3_ALIAS#.PRODUCT P ON P.PRODUCT_ID=IR.PRODUCT_ID
JOIN #DSN3_ALIAS#.PRODUCT_CAT PC ON P.PRODUCT_CATID=PC.PRODUCT_CATID
WHERE
P.PRODUCT_ID=<cfqueryparam value="#attributes.product_id#" cfsqltype="cf_sql_integer">
GROUP BY C.COMPANY_ID,C.FULLNAME
ORDER BY TOTAL DESC
答案 1 :(得分:0)
我希望我明白你要做什么,抱歉,如果我没有
SELECT FULLNAME,COMPANY_ID
FROM (
SELECT SUM(I.GROSSTOTAL) AS TOTAL,
SUM(I.OTHER_MONEY_VALUE/1.18) AS OTHER_TOTAL,
COUNT(IR.PRODUCT_ID) AS NO_PRODUCTS
FROM COMPANY C
JOIN #DSN2_ALIAS#.INVOICE I ON C.COMPANY_ID=I.COMPANY_ID
JOIN #DSN2_ALIAS#.INVOICE_ROW IR ON I.INVOICE_ID=IR.INVOICE_ID
JOIN #DSN3_ALIAS#.PRODUCT P ON P.PRODUCT_ID=IR.PRODUCT_ID
JOIN #DSN3_ALIAS#.PRODUCT_CAT PC ON P.PRODUCT_CATID=PC.PRODUCT_CATID
WHERE P.PRODUCT_ID=<cfqueryparam value="#attributes.product_id#" cfsqltype="cf_sql_integer">
ORDER BY TOTAL DESC )
GROUP BY COMPANY_ID,FULLNAME