2016-10-19 73 views
0

我在數據庫管理系統中有一個任務,我必須爲給定的問題編寫查詢。 我有4個問題,其中我解決了3個問題,並堅持最後一個問題。SQLite - 如果爲空返回0

詳情:

  • 使用奇努克數據庫https://chinookdatabase.codeplex.com/)的1.4版本。
  • 的SQLite數據庫瀏覽器
  • 奇努克sqlite的AutoIncrementPKs.sqlite文件與奇努克文件的目錄是我在

問題陳述所使用的數據庫: 編寫一個查詢根據他們作爲支持代表的客戶發票的金額數據生成一份排名的員工名單。結果集(見下圖)對於所有員工(即使是那些不支持任何客戶的)應該有以下字段(按順序):ID(e_id),名字(e_first name),姓氏(e_last_name),標題(e_title)和發票總額(total_invoices)。這些行應按發票總額(最高優先)排序,然後按姓氏(按字母順序排列),然後名稱(按字母順序排列)。發票總額應以美元符號($)開頭,小數點後有兩位數(適當舍入);在員工沒有任何發票的情況下,您應該輸出0.00美元,而不是NULL。您可能會發現查看SQLite的IFNULL,ROUND和PRINTF函數很有用。

所需的輸出:

enter image description here

我的查詢:

Select Employee.EmployeeId as e_id, 
      Employee.FirstName as e_first_name, 
      Employee.LastName as e_last_name, 
      Employee.Title as e_title, 
      '$' || printf("%.2f", Sum(Invoice.Total)) as total_invoices 
From Invoice Inner Join Customer On Customer.CustomerId = Invoice.CustomerId 
        Inner Join Employee On Employee.EmployeeId = Customer.SupportRepId 
Group by Employee.EmployeeId 
Having Invoice.CustomerId in 
(Select Customer.CustomerId From Customer 
Where Customer.SupportRepId in 
     (Select Employee.EmployeeId From Employee Inner Join Customer On Employee.EmployeeId = Customer.SupportRepId) 
) 
order by sum(Invoice.Total) desc 

我的輸出:

enter image description here

如您所見,前三行是正確的,但後面的行不會被打印,因爲員工沒有任何發票,因此EmployeeID爲空。

如何在這種情況下打印行? 我試過合併ifnull功能,但我不能讓他們的工作。

我真的很感激,如果有人可以修改我的查詢來獲得匹配的解決方案。 謝謝!

P.小號:這是奇努克數據庫的模式

enter image description here

回答

1

經常發生,它更容易使用子查詢:

SELECT EmployeeId, 
     FirstMame, 
     LastName, 
     Title, 
     (SELECT printf("...", ifnull(sum(Total), 0)) 
     FROM Invoice 
     JOIN Customer USING (CustomerId) 
     WHERE Customer.SupportRepId = Employee.EmployeeId 
     ) AS total_invoices 
FROM Employee 
ORDER BY total_invoices DESC; 

(內部聯接可以使用子查詢來代替了。 )

但是,您應該證明您已經瞭解了outer joins,如果找不到匹配的行,將生成包含空值的虛假行:

... 
FROM Employee 
LEFT JOIN Customer ON Employee.EmployeeId = Customer.SupportRepId 
LEFT JOIN Invoice USING (CustomerID) 
... 

如果你想成爲一個自作聰明,與total(...)更換ifnull(sum(...), 0)

+0

非常感謝。有效 :) – user3397557