Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
ravininave
Posting Yak Master
111 Posts |
Posted - 2010-06-25 : 15:02:28
|
Hi All,This is My TableId Total1 12 11 14 11 16 11 18 16 18 18 1In above case 1 has a total of 4, means 1 has came 4 times means if I group by on id the output would be1 42 14 16 28 3Now I've to sum the total likeif Total is greater than 2 then 2 else totalMeans it could be something likesum(Case when sum(Total) > 2 then 2 else sum(Total) end)But it won't workIn short I've to sum the total for those ID which are lesser than two or equal to two and if total is greater than two then it should assume it as 2.How could I do it.VB6/ASP.NET------------------------http://www.nehasoftec.com |
|
hai
Yak Posting Veteran
84 Posts |
Posted - 2010-06-25 : 15:19:29
|
something like this?select id, (case when sum(total) >= 2 then 2 else sum(total) end) from (select 1 as id, 1 as totalunion allselect 2, 1union allselect 1, 1union allselect 4, 1union allselect1, 1union allselect6, 1union allselect1, 1union allselect8, 1union allselect6, 1union allselect8, 1union allselect8 ,1)Bgroup by id |
 |
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2010-06-25 : 16:22:22
|
no need to "case" or double sum or anything else.see this exampleselect id, sum(total)from (select id, total, row_number() over (partition by id order by total) AS recidfrom yourtablenamehere) AS dwhere recid <= 2group by id N 56°04'39.26"E 12°55'05.63" |
 |
|
ravininave
Posting Yak Master
111 Posts |
Posted - 2010-06-25 : 19:41:51
|
quote: Originally posted by Peso no need to "case" or double sum or anything else.see this exampleselect id, sum(total)from (select id, total, row_number() over (partition by id order by total) AS recidfrom yourtablenamehere) AS dwhere recid <= 2group by id N 56°04'39.26"E 12°55'05.63"
No it doesn't worksthe output should be 8 Only.I just wanna Total.VB6/ASP.NET------------------------http://www.nehasoftec.com |
 |
|
ravininave
Posting Yak Master
111 Posts |
Posted - 2010-06-25 : 20:01:58
|
See What I'd done but there should be some simple sql statementDECLARE @DateTable AS TABLE (ID int,Total int,FinalTotal int)Insert into @DateTableSelect ID,sum(Total) as sTotal,Case When sum(Total) >2 then 2 else sum(Total) end as FinalTotal from MyTableName Group by ID Order by sTotalSelect sum(FinalTotal) from @DateTable;Output =8VB6/ASP.NET------------------------http://www.nehasoftec.com |
 |
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2010-06-26 : 01:37:51
|
[code];with cte(id, total) AS (select id, sum(total)from (select id, total, row_number() over (partition by id order by total) AS recidfrom yourtablenamehere) AS dwhere recid <= 2group by id)select sum(total) from cte[/code] N 56°04'39.26"E 12°55'05.63" |
 |
|
|
|
|
|
|