SQL Server SUM function in view
-
13-06-2021 - |
Question
I have a view with fields:
typeId, type int
price, type decimal(15,4))
Price is calculated value.
What I would like is to add another calculated column (totalPrice
) in the select statement that would sum all prices for records with same id giving me the result (assuming there are four rows in the view):
typeId price totalPrice
1 10,000 30,000
1 15,000 30,000
1 5,000 30,000
2 10,000 10,000
Thank you.
Solution
Assuming your existing view is named TheSummary. Rename it to x_TheSummary
Create a new view which bears the old name of the renamed view.
create view TheSummary as
select x.*, g.totalPrice
from x_TheSummary x
join
(
select typeId, sum(price) as totalPrice
from x_TheSummary
group by typeId
) as g on g.typeId = x.typeId
This way, your new view won't have any breaking changes to apps that depends on old view name
By the way, since you are using SQL Server 2008, you can use the following windowing-query too, the query above works on non-windowing-capable RDBMS though.
create view TheSummary as
select x.*, sum(totalPrice partition by typeId) as totalPrice
from x_TheSummary x
It's a lot simpler
@ivan-83 For a second, I thought SQL Server 2008 doesn't support windowing on partition. I'm thinking too much of this construct(running total) that doesn't work on SQL 2008, yet it works on SQL 2012.
SELECT i, sum(i) over(order by i) as rt
FROM (values(1),(9),(7),(6)) as x(i)
The running total query doesn't work on SQL 2008: http://www.sqlfiddle.com/#!3/d41d8/1539
And it now works on SQL 2012: http://www.sqlfiddle.com/#!6/d41d8/111
Outputs:
| I | RT |
----------
| 1 | 1 |
| 6 | 7 |
| 7 | 14 |
| 9 | 23 |
To sum it up, SQL Server 2012 not only it supports windowing on partition, it also supports windowing on row-by-row basis. SQL Server 2008 supports windowing on partition only. So @ivan-83 solutions works too. For this, I upvote your answer
OTHER TIPS
select *, (select sum(price)
from view as v2
where v2.typeId = v1.typeId) as totalPrice
from view as v1
Try this
.
.
.
dbo.SklepOcenjenaVrednost.StevilkaNarocila,
CAST(CASE dbo.CstPostavkaSklepa.DDVID WHEN 1
THEN dbo.CstPostavkaSklepa.CenaSkupajDDV * 1.085
WHEN 2 THEN dbo.CstPostavkaSklepa.CenaSkupajDDV * 1.2
ELSE dbo.CstPostavkaSklepa.CenaSkupajDDV END AS decimal(15, 4)) AS CenaPostavkeZDDV
, (select sum (CAST(CASE dbo.CstPostavkaSklepa.DDVID
WHEN 1 THEN dbo.CstPostavkaSklepa.CenaSkupajDDV * 1.085
WHEN 2 THEN dbo.CstPostavkaSklepa.CenaSkupajDDV * 1.2
ELSE dbo.CstPostavkaSklepa.CenaSkupajDDV END AS decimal(15, 4)))
from dbo.CstPostavkaSklepa as CstPostavkaSklepa2
where dbo.CstPostavkaSklepa.SklepID = CstPostavkaSklepa2.SklepID ) as CenaSklepaZDDV
FROM dbo.CstSklep INNER JOIN
dbo.ActiveProcess ON dbo.CstSklep.ProcID = dbo.ActiveProcess.Id INNER JOIN
dbo.CstPostavkaSklepa ON dbo.CstSklep.SklepID = dbo.CstPostavkaSklepa.SklepID INNER JOIN
.
.
.