在开始之前,我想让你知道我正在使用着名的微软Northwind数据库。
所以,我需要创建一个函数来检索以下结果集:
Query需要创建一个函数,该函数接收国家名称(表Orders的shipCountry字段)作为参数,并且必须输出雇员的姓氏(表Employees的lastName字段)和总金额每个员工每年(1996,1997,1998)在该职能的输入中收到的收入。
当我谈到他们所赚取的总收入时,我指的是总结订单的所有单价。 (我使用了字段:unitPrice,表格的数量和折扣[订单明细])
在这里,我向你们展示我所做的查询,这样你就可以更好地了解我想要做什么,我的问题是我不知道在哪里放置国名的条件(正如我所说的那样)必须根据我们在函数中插入的国家/地区显示信息:
CREATE FUNCTION fn_listAnualAmounts(@country NVARCHAR)
RETURNS TABLE
AS
BEGIN
DECLARE @anio96 MONEY, @anio97 MONEY, @anio98 MONEY
SET @anio96 = (SELECT SUM((od.UnitPrice - od.Discount)*od.quantity) as [Año 1996]
FROM [Order Details] od
left join Orders o on o.OrderID = od.OrderID
left join Employees e on e.EmployeeID = o.EmployeeID
GROUP BY YEAR(o.OrderDate),e.EmployeeID
HAVING YEAR(o.OrderDate) = '1996')
SET @anio97 = (SELECT SUM((od.UnitPrice - od.Discount)*od.quantity) as [Año 1997]
FROM [Order Details] od
left join Orders o on o.OrderID = od.OrderID
left join Employees e on e.EmployeeID = o.EmployeeID
GROUP BY YEAR(o.OrderDate),e.EmployeeID
HAVING YEAR(o.OrderDate) = '1997')
SET @anio98 = (SELECT SUM((od.UnitPrice - od.Discount)*od.quantity) as [Año 1998]
FROM [Order Details] od
left join Orders o on o.OrderID = od.OrderID
left join Employees e on e.EmployeeID = o.EmployeeID
GROUP BY YEAR(o.OrderDate),e.EmployeeID
HAVING YEAR(o.OrderDate) = '1998')
RETURN (SELECT e.LastName, @anio96, @anio97, @anio98
FROM Employees e)
END
GO
此处您有northwind数据库图表
非常感谢你们所有人!
答案 0 :(得分:0)
只需使用条件聚合:
SELECT e.LastName,
SUM(CASE WHEN YEAR(o.OrderDate) = 1996
THEN (od.UnitPrice - od.Discount)*od.quantity
END) as total_1996
SUM(CASE WHEN YEAR(o.OrderDate) = 1997
THEN (od.UnitPrice - od.Discount)*od.quantity
END) as total_1997,
SUM(CASE WHEN YEAR(o.OrderDate) = 1998
THEN (od.UnitPrice - od.Discount)*od.quantity
END) as total_1998
FROM [Order Details] od LEFT JOIN
Orders o
ON o.OrderID = od.OrderID LEFT JOIN
Employees e
ON e.EmployeeID = o.EmployeeID
GROUP BY e.EmployeeId, e.LastName;