我写了一个查询,我想显示"客户编号" (CUSTOMER表),"发票数量" (INVOICE表),这是每个客户的总发票,以及" Total Cus Purchases" (通过加入CUSTOMER,INVOICE和LINE表计算得出),这是属于每个客户的所有发票中所有购买的总和。
第一个查询吐出错误的"发票数量"。
--First Query
SELECT CUSTOMER.CUST_NUM AS "Customer Number",
COUNT(INVOICE.INV_NUM) AS "Number of Invoices",
SUM(LINE.LINE_UNITS * LINE.LINE_PRICE) AS "Total Cus Purchases"
FROM CUSTOMER
JOIN INVOICE
ON CUSTOMER.CUST_NUM = INVOICE.CUST_NUM
JOIN LINE
ON INVOICE.INV_NUM = LINE.INV_NUMBER
GROUP BY CUSTOMER.CUST_NUM;
Customer Code Number of Invoices Total Cus Purchases
1000 5 188.72
1003 6 432.8
1001 3 34.92
1002 1 70.44
但是,第二个查询(省略LINE的连接语句时会注意到这一点,用于计算" Total Cus Purchases")吐出正确的"发票数量&#34 ;
--Second Query
SELECT
CUSTOMER.CUST_NUM AS "Customer Number",
COUNT(INVOICE.INV_NUM) AS "Number of Invoices"
FROM INVOICE
JOIN CUSTOMER ON INVOICE.CUST_NUM = CUSTOMER.CUST_NUM
GROUP BY CUSTOMER.CUST_NUM;
Customer Code Number of Invoices
1000 3
1003 2
1001 2
1002 1
如何更正First Query以使其吐出第二个查询中显示的值?
(注意:购买的cus总数是正确的,只是"发票数量"列错了。)
答案 0 :(得分:1)
COUNT(DISTINCT)
解决了计数问题,但您也可以通过将JOIN
移到CUSTOMER
表来简化查询:
SELECT i.CUST_NUM AS "Customer Number",
COUNT(DISTINCT i.INV_NUM) AS "Number of Invoices",
SUM(l.LINE_UNITS * l.LINE_PRICE) AS "Total Cus Purchases"
FROM INVOICE i JOIN
LINE l
ON i.INV_NUM = l.INV_NUMBER
GROUP BY i.CUST_NUM;
您正在使用CUST_NUM
,它位于INVOICE
表中。