我的SQL Server中有一个名为Product
的表,其列为ID, NAME, YEAR, COST
示例数据:
ID NAME YEAR COST
----------------------------------
1 A 2006 05 03 4
2 B 2006 04 01 5
3 C 2001 05 01 6
4 D 2002 05 02 7
5 E 2003 04 01 8
我想只将YEAR作为输入,如2006年作为输入,我想要一个显示当年所有增加成本的输出。我该怎么做?
预期输出:
ID NAME YEAR TOTAL
-------------------------------
1 A 2006 05 03 9
2 B 2006 02 01 9
3 C 2001 05 01 6
4 D 2002 05 02 7
5 E 2003 04 01 8
答案 0 :(得分:3)
将sum()
与over()
子句一起使用,并按year()
分区。
select T.ID,
T.Name,
T.Year,
sum(T.Cost) over(partition by year(T.Year)) as Cost
from YourTable as T
SUM (Transact-SQL)
OVER Clause (Transact-SQL)
YEAR (Transact-SQL)
在参数@Year
上过滤上述查询将如下所示:
select T.ID,
T.Name,
T.Year,
sum(T.Cost) over() as Cost
from YourTable as T
where T.Year >= dateadd(year, @Year-1900, '19000101') and
T.Year < dateadd(year, @Year-1899, '19000101')
答案 1 :(得分:0)
使用子查询:
SELECT ID, NAME, year, (select Sum(Cost)
from Product P1
where YEAR(P1.year) = YEAR(P2.year)) as Cost
FROM Product P2
WHERE YEAR(year) = 2006 --your parameter here
演示:http://sqlfiddle.com/#!3/9345d/10
带参数的存储过程如下所示:
CREATE PROCEDURE ProcedureName
-- Add the parameters for the stored procedure here
@Year int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
select ID, Name, year, (select Sum(Cost)
from Products P1
where YEAR(P1.year) = YEAR(P2.year)) as Cost
from Products P2
WHERE YEAR(year) = @Year
END
GO