我刚开始使用SQL,并且用这种语言思考时遇到了一些困难。
我现在有一个任务,需要在表中使用前几列中的值创建新列。该计算基于很少的条件。在SQL中甚至可以轻松做到这一点吗?
假设我有一个名为dbo.country_sales的表,
Select *
From dbo.country
产生
CountryName, Year, Sales
—————————
Argentina, 2015, 10
Argentina, 2017, 22
Florida, 2015, 10
Florida, 2017, 8
Germany, 2015, null
Germany, 2017, null
我需要在2015年至2017年之间创建第四列销售发展情况(2017年销售-2015年销售),因此表格如下所示:
CountryName, Year, Sales, Development
—————————
Argentina, 2015, 10, 12
Argentina, 2017, 22, 12
Florida, 2015, 10, -2
Florida, 2017, 8, -2
Germany, 2015, null, null
Germany, 2017, null, null
我知道如何在select语句中创建它,但是它仅计算1个值。试图搜索了几个小时,但没有找到简单的东西。
感谢您的帮助。 兰
答案 0 :(得分:3)
一种简单的方法使用窗口函数和条件聚合:
select c.*,
sum(case when year = 2017 then sales
when year = 2015 then - sales
end) over (partition by country) as diff_2017_2015
from dbo.country c
where year in (2015, 2017);
答案 1 :(得分:1)
您可以使用CTE预先计算值。例如:
with a as (
select countryname, year, sales from t where year = 2015
),
b as (
select countryname, year, sales from t where year = 2017
),
c as (
select a.countryname, b.sales - a.sales as development
from a
join b on a.countryname = b.countryname
)
select a.*, c.development
from a
join c on c.countryname = a.countryname
union
select b.*, c.development
from b
join c on c.countryname = b.countryname
order by countryname, year
答案 2 :(得分:0)
对于稍微有些异国情调的解决方案(可能会为您将来的使用提供更大的灵活性),您可以创建一个辅助函数。
CREATE FUNCTION dbo.udf_SalesDiff(
@CountryName VARCHAR(50)
,@LookbackYear INT
,@CurrentSales MONEY
)
RETURNS MONEY
BEGIN
DECLARE @Diff MONEY
SELECT @Diff = @CurrentSales - [Sales]
FROM dbo.CountrySales
WHERE [CountryName] = @CountryName AND [Year] = @LookbackYear
RETURN @Diff
END
在哪里可以像这样使用它:
SELECT
[CountryName]
,[Year]
,dbo.udf_SalesDiff([CountryName],2015,[Sales]) AS Development
FROM dbo.CountrySales
WHERE [Year]=2017
将产生:
CountryName | Year | Development
--------------------------------
Argentina | 2017 | 12
Florida | 2017 | -2
Germany | 2017 | NULL