我有一张表列出了员工的服务电话。我有一个视图设置来查看表中的发票总和。
Select EmployeeID, SUM(InvoiceAmount) as "Total $ Amount Of Calls For January"
From Calls
WHERE Date BETWEEN '2013/01/01' AND '2013/01/31'
Group by EmployeeID
这很有效,但我每个月要查看12次,这看起来有点多余。我希望能够使用子查询显示EmployeeID,然后列出每个月的总数。
EmployeeID JAN FEB MAR APR ...
john 444 555 342 654
jim 945 675 232 465
我已经尝试了很多东西,甚至无法接近......我需要这样的东西,但是有效......
SELECT
EmployeeID,
(SELECT SUM(InvoiceAmount) FROM Orders WHERE DATE BETWEEN '2013/01/01' AND '2013/01/31') AS JAN,
(SELECT SUM(InvoiceAmount) FROM Orders WHERE DATE BETWEEN '2013/02/01' AND '2013/02/28') AS FEB,
(SELECT SUM(InvoiceAmount) FROM Orders WHERE DATE BETWEEN '2013/03/01' AND '2013/03/31') AS MAR,
FROM Calls
答案 0 :(得分:3)
您可以这样做:
SELECT EmployeeID,
SUM(
CASE
WHEN strftime('%m', Date) = '01'
THEN InvoiceAmount
ELSE 0
END) AS 'Jan',
SUM(
CASE
WHEN strftime('%m', Date) = '02'
THEN InvoiceAmount
ELSE 0
END) AS 'Feb',
...
SUM(
CASE
WHEN strftime('%m', Date) = '12'
THEN InvoiceAmount
ELSE 0
END) AS 'Dec'
FROM Calls
WHERE Date BETWEEN '2013-01-01' AND '2013-12-31'
GROUP BY EmployeeID
如果您正在查看某一年,这种情况很有效。