0

我在计算分组查询中的 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 和它的全名分组的,但是每张发票里面有多个产品,因此变量 no_products 定义错误:(

我怎样才能得到正确的计数?

4

2 回答 2

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
于 2012-05-29T14:58:52.323 回答
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
于 2012-05-29T15:03:02.737 回答