Write a SELECT statement that returns one row for each vendor in the Invoices table that contains these columns: The vendor_id column from the Vendors table The sum of the invoice_total columns in the Invoices table for that vendor

SELECT  
    distinct vendor_id, SUM(invoice_total) AS Invoice_totals 
FROM 
    invoices i 
    join vendors v using (vendor_id); 

我可以在没有 SUM(invoice_total) 的情况下显示所有 34 个 vendor_id,但是一旦我添加它,它就会将它们合并为一个。我怎样才能避免这种情况发生?

请您参考如下方法:

不要将 select distinctsum() 一起使用。使用分组方式。这使得查询的意图更加清晰。

其次,您需要一个左连接:

SELECT vendor_id, SUM(i.invoice_total) AS Invoice_totals 
FROM vendors v LEFT JOIN 
     invoices i 
     using (vendor_id) 
GROUP BY vendor_id; 


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!