Summing Only The Greatest 5 Values In Each Group

Jan 10, 2008

Hello,
Here's one way to sum only the top 5 (greatest 5) values per group.
I assume there is a table called IdValues that contains two columns: id int, value int.

declare @lastId int
declare @value int
declare @count int
declare @idList varchar(5000)
declare @valuelist varchar(5000)
set @count=0
set @lastId = -1
set @value = 0
set @idList=''
set @valuelist=''

select
@count=(case when @lastId<>id then 1 else @count+1 end),
@value=(case when @lastId<>id then value when @count<=5 then @value+value else @value end),
@idList=(case when @lastId<>id then cast(id as varchar)+','+@idList else @idList end),
@valuelist=(case when @lastId<>id then cast(@value as varchar)+','+@valuelist else cast(@value as varchar)+','+right(@valuelist,len(@valuelist)-charindex(',',@valuelist)) end),
@lastId=id
from IdValues
order by id desc, value desc

select @idList,@valuelist

It's a funny approach. I'd be interested to see a better method. In MySQL it is possible to do this much better and have it produce an actual resultset (since MySQL allows you to assign variables and product a resultset in the same query).

I also noticed something interesting. If you do any operation on the order-by columns, the query doesn't work. For example, if I do:
order by id+0 desc, value desc
something funny happens and you only get one id and one value in the list variables. Maybe someone else who actually some idea of how SQL Server works can explain this.

Thanks,
Thomas

View 3 Replies


ADVERTISEMENT

Report Services 2000 Totals On Group Are Incorrect. Summing Duplicate Values

Dec 19, 2007

Hello Everyone
I've created a report with a simple dataset that is similar to this

City , RequestID, Request Amount, ClaimID, ClaimAmount
El Monte 791 52,982.00 2157 41,143.75
El Monte 3691 11,838.00 3140 8,231.14
El Monte 3691 11,838.00 3141 990.00
El Monte 3691 11,838.00 3142 2,615.00


So I group by City, RequestID. On the first group I specified the expression to be City and in the header I list the city and in the footer I list the sum of Request amount. On the second group I specified the group by Request so in the header I placed requestID and on the footer I placed Request Amount. I set request information to hide the duplicates and I even add =Sum(Fields!RequestApprovedGrandTotal.Value,"GroupByRequestID") the scope of the group. But this is what I get:


For requestID = 3691 for Request Amount is 35,514.00 not 11,838.00. All the claim sums are correct and they are located on the detail row.



I've read that a work around is to create multiple dataset but I honestly believe that something as simple as this should work on the reporting server 2000. So I've come to the conclusion that I must be doing something wrong. Can someone give me a hand on this. Thanks.

View 6 Replies View Related

Summing Textboxes With Values From Diff. Datasets

Apr 28, 2008



hello,

I have the following and what to do SUM the valueS in each in another textbox, what is the proper method?



=count(Fields!Month_Submitted.Value, "SALES")

=count(Fields!Month_Submitted_1.Value, "SALESDIR")

=count(Fields!Month_Submitted_2.Value, "SALESVP")

=count(Fields!Month_Submitted_3.Value, "CREDIT")



Thanks,
Rhonda

View 8 Replies View Related

Transact SQL :: Best Way To Make A Function For Summing Arbitrary Number Of Times Values

Jun 22, 2015

How is the best way to make a function for summing an arbitrary number of times values (table parm?)- I 've read it's necessary to convert to seconds, sum then convert back, but Im' wondering if there's an alternative.

Here's the example I want to sum:
00:02:01:30
00:01:28:10
00:01:01:50
00:06:50:30
00:00:01:50

View 8 Replies View Related

Reporting Services :: Export Excel Formula For Summing Column Values

Jun 22, 2009

In SQL server Reporting service we need to export excel formula for summing column values. scenario : After generating report we are exporting report to excel file using report viewer.when user will modify a column value we need to calculate(update) automatically sum of the column values.Basically we are setting excel formula.

View 3 Replies View Related

Reporting Services :: SSRS - Summing Up Positive And Negative Values Alone From Single Column?

Sep 18, 2015

MS SQL Server 2008 R2

I have both positive and negative values in a single column, where I want sum total of positive values & negative values. Is there any Expression for this to sort out.

View 8 Replies View Related

Greatest Value

Mar 15, 2006

Hi all. I'm looking for assistance to get the greatest value from 3 or more different columns. I'm assuming that the best way is to put the columns into a temp table and use 'max' function to return the greatest value but don't know how to code it. Thanks in advance.

View 7 Replies View Related

GREATEST AND LEAST

Apr 24, 2007

Hi All,

Is there any equivalent of GREATEST(something) and LEAST(something)
in SQL server 2000

Thanks in advance.

vishu
Bangalore

View 9 Replies View Related

Greatest Value

Mar 14, 2006

Hi all. I'm looking for assistance to get the greatest value from 3 ormore different columns. I'm assuming that the best way is to put thecolumns into a temp table and use 'max' function to return the greatestvalue but don't know how to code it. Thanks in advance.*** Sent via Developersdex http://www.developersdex.com ***

View 2 Replies View Related

Greatest And Least Functions

Mar 2, 2001

1.I am trying to write following query in SQLserver(this is oracle query),
IS their any equivalent for GREATEST and LEAST functions in SQLServer ???

Update mwebtemp
Set Temp_amount1 = (SELECT SUM(AuthAttr_Amount*(num_Business_Days
(GREATEST(AuthAttr_Start_Date, @dtstartdate),
LEAST(AuthAttr_Finish_Date, @dtenddate))))
.....where...
etc...
.....

Note: this is part of a stored procedure...

2. Also how do you write and call a function in SQLServer (syntax ??), eg.num_Business_Days
is a function returning number of business days between the 2 dates....

thanks a lot

View 1 Replies View Related

SQL With Greatest Date

Nov 7, 2006

Here is my SQL statementSELECT a.name, b.meterno, c.meterstatus, d.accountno, d.creation_dateFROM fmdata.location a, cisdata.service_meters b, cisdata.meter_master c,cisdata.Account_Master dWHERE a.location_id = b.location_id AND b.meterno IS NOT NULL AND b.meterno= c.meterno AND a.location_id = d.location_idORDER by meterstatus, nameHere is my resultsNAME METERNO METERSTATUS ACCOUNTNO CREATION_DATE01010004 20512944 Active 101000402 7-Feb-200201010004 20512944 Active 101000401 8-May-199701010005 25917180 Active 101000501 27-May-200301011001 13646231 Active 101100102 17-Mar-199901011002 18389246 Active 101100201 29-Apr-199401011003 84473845 Active 101100301 24-Apr-199701012002 47511850 Active 101200202 26-Jan-199601013001 35653963 Active 101300101 28-Feb-1979If you notice I'm getting two 01010004 under the NAME column. I would likethe SQL statement to select the greatest CREATION_DATE if there areduplicate NAME'S. So in this case, it would select the top 01010004 since ithas the greatest CREATION_DATE.thanks in advancebart

View 2 Replies View Related

SQL - Getting First Or Last Values For A Group...

Mar 13, 2004

I have this values in my SQL Database....

The day Format I am ussing is dd/mm/yyyy

NumEstado NumMunicipio NumComunidad NumFamilia NumNiño FechaVisita Peso Talla
7 15 1 12 14 30/06/2000 8.5 73
7 15 1 12 14 09/08/2000 8.6 0
7 15 1 12 14 09/09/2000 8.7 0
7 15 1 12 14 22/01/2001 9 0
7 15 1 12 14 01/07/2001 10.4 0
7 15 1 12 14 14/01/2002 11.6 0
7 15 1 12 14 18/03/2002 12.9 0
7 15 1 12 14 26/05/2002 13.2 0
7 15 1 12 14 21/07/2002 13.5 0
7 15 1 12 14 07/01/2003 14.5 0
7 15 1 12 14 04/03/2003 14.6 100
7 15 1 12 14 22/07/2003 15.2 100
7 15 1 12 14 16/09/2003 17 0
7 15 1 12 14 19/11/2003 17.6 104
7 15 1 12 14 07/02/2004 0 0

And now, if I use this instruccion:

SELECT TOP 100 PERCENT NumEstado, NumMunicipio, NumComunidad, NumFamilia, NumNiño, MIN(FechaVisitaRealizada), MIN(Peso), MIN(Talla)
FROM dbo.VisitaPromotor
GROUP BY NumEstado, NumMunicipio, NumComunidad, NumFamilia, NumNiño
HAVING (NumEstado = 7) AND (NumMunicipio = 15) AND (NumComunidad = 1) AND (NumFamilia = 12) AND (NumNiño = 14)

I received this result:
7 15 1 12 14 30/06/2000 0 0

But I do not want this result, I want all the values within the record that it has the Min Date. this is, I want a Sql Query that giveme this result:

7 15 1 12 14 30/06/2000 8.5 73

Becuase these are the values for the Min Date in this group of records.

Or, in other hands, if I want the values for the Max Date I should recieved this results:

7 15 1 12 14 07/02/2004 0 0

Because these are the values for the Max Date.....

Thanks a lot for your help.....

View 1 Replies View Related

Get Some Values From A Group

Aug 16, 2007

Hello,

here's my problem. There's table t with:

year, id, price
2000 1 100
2000 1 200
2000 2 100
2000 3 500
2000 4 100
2001 1 100
2001 2 300
...

I need a way, to get those prices, so I have e.g. 3 Groups for every year with the same number of elements in it. Here's the bakground:
My employer wants a report for the sold objects in each year classified by upper, middle and lower price level. The biggest problem is, that I cannot define prices manually. What I have to do, is to order prices in each group (e.g. year), combine that with row_number(), devide row_count by 3, do a loop with step (row_number / 3) and get price at that position.
But getting those prices gives me the willies. I just discoverd the "MODEL" Clause. Do you think, that can help me solve the problem?
Maybe you have some tips.
Thanks!

View 4 Replies View Related

Need To Group Values

Dec 6, 2014

my table stucture like

date HourType hours HourValue status
day1 m 1 1 y
day1 m 2 1 y
day1 m 3 1 y
day1 a 4 0 n
day1 a 5 0 n
day1 a 6 0 n

day2 m 1 1 y
day2 m 2 1 y
day2 m 3 1 y
day2 a 4 0 y
day2 a 5 1 y
day2 a 6 1 y

my day1 afternoon all hours 0, and day2 4th hour only 0,i need to status column that must be 'N' when all afternoon hours or morning hours is 0, if only one hour 0 means that must 'Y',how do set a status column like above.

View 2 Replies View Related

Very Urgent Greatest And Least Functions

Apr 6, 2001

I have to to find the greatest and least values from the set of values which are from the different columns.

Eg. Select greatest(tab1.date1, tab2.date2), least(tab1.date3, tab2.date4)
from tab1, tab2
where....

tab1 and tab2 are the tables and
date1, date3 are the columns from tab1
date2, date4 are the columns from tab2

Is there any easy way to do this in SQL server ?

MAX and MIN will not work here as these are not the max and min from the same column they are from the different tables and columns.

Thanks

View 4 Replies View Related

Greatest Function In TSQL

Aug 20, 2007

Hi All,
I need to find the highest of two numbers and lowest of the two numbers.
I read on the web that Greatest and least functions in sql can help me do that.
but when i use
greatest in my query it gives me this error

GREATEST is not a recognized built-in function name.
all I have is

declare @first int, @second int
set @first='12'
set @second='14'
select GREATEST(@first,@second)

Can somebody point me in the right direction.
Thanks so much

View 8 Replies View Related

Group By For Different Column Values

Feb 15, 2012

I have 2 tables which have the data as follows:

A:
Id Reason Amount Subject RecordNo
1 Gift 100 first 11
2 Gift Reason 200 second 12
3 Gift Reason 100 first 11

The result that I want is :

Reason Amount Subject
ALL 200 first
i used the following query

select
case when Grouping(B.Subject) <> '' then 'ALL' else B.Subject End as Subject ,
case when Grouping(B.reason) <> '' then 'ALL' else B.Reason END as Reason,
SUM(B.amount) as amount
from B
where B.RecordNo = 11
group by grouping sets (B.Reason,B.Subject)

but it's giving me 3 rows in return.

I want only one summation row. How can i get that?

View 1 Replies View Related

How Do I Just SUM The Group Header Values?

Jun 21, 2007

Here's my table so far in RS:



Facility Name | Claim | Fee | Value | Payment | Table Header
Wisconsin West | | | | | Group1 Header
| 2356 | $45 | $23 | | Group2 Header
| | | | $21 | Details
| | | | $7 | Details
| | | | $16 | Details
| 2357 | $85 | $47 | | Group2 Header
| | | | $21 | Details
| | | | $9 | Details
| | | | $13 | Details
| 2358 | $105 | $65 | | Group2 Header
| | | | $35 | Details
| | | | $12 | Details
| | | | $20 | Details
Facility Totals | 3 | $705 | $405 | $154 | Group1 Footer



*Notes = Table and Group2 footers are hidden and contains nothing. The last column is detailing what level each line is and not actually part of the table.



I believe my issue is with the SUM function and how or where to place it. In the Payment field, the SUM function is adding correctly, but for the Fee and Value field, the SUM fuction is adding as if every line item in the payment field had the fee and value amount, hence the huge amount.



How can make the Fee field total to $235 (45+85+105) instead of $705 (45+45+45+85+85+85+105+105+105); the same goes for the Value field of $135 (23+47+65) instead of $405 (23+23+23+47+47+47+65+65+65).



Below are the expressions I have in place at the Group1 Footer for the Claim, Fee, Value, and Payment fields respectively:



=CountDistinct(Fields!ClaimNumber.Value

=Sum(Fields!dAmount.Value)

=Sum(Fields!Value.Value)

=Sum(Fields!cAmount.Value)



I've tried playing with the scope, but to no avail. Any ideas or maybe I'm doing it all wrong? It's almost as if I need a SumDistinct if such a thing exist.



In the meantime, I'm doing some serious researching. Thanks!

View 1 Replies View Related

Selecting One Greatest Number From Two Columns?

Jul 20, 2005

I have table1 and table2.In table1 I have a column of numbers, numbers1.In table2 I have a column of numbers, numbers2.I'd like to select the highest number represented in either column.Example:table1:column1--------------345565643656555676table2:column2--------------3456564556456456456456The number I would want would be 56456 since it's the largest numberout of all combined.How can I get that number with one select statement?--[ Sugapablo ][ http://www.sugapablo.com <--music ][ http://www.sugapablo.net <--personal ][ Join Bytes! <--jabber IM ]

View 1 Replies View Related

Find The Greatest Of Three Columns Per Each Row And Display

Nov 15, 2006

Hi,

i have a problem where in i have to display the greatest marks scored by each student.

How can i do this?? Is there any built in TSQL function.

Rgds..,

Aazad

View 4 Replies View Related

Implementing Oracle's GREATEST And LEAST Functions In T-SQL

Sep 15, 2006

Has anybody been successful in doing this? I've seen a few articles on the web, but none for free....

View 4 Replies View Related

Any Function In T-SQL Thats Similar To GREATEST() IN Orcl.

Dec 6, 2007


Is there any Function in T-SQL thats similar to GREATEST() IN Orcl?

Iam trying to find the greatest of two DATETIME datatype Fields in my 'select's.
If there is no in built function, Whats the best approach?

View 14 Replies View Related

How Do I Pass A Group Of Values In A Parameter? Like Where Id In (@Value)

Mar 30, 2006

I want to do something like this
SELECT     LocationID, Description, ActiveFROM         dbo.CapLocationWHERE     (Active = 1)
AND (LocationID NOT IN (2)) AND
(LocationID NOT IN (@LocationID) OR @LocationID IS NULL)ORDER BY Description
For the life of my I can not figure out how to pass a group of values like 1,2,3.
Any help would be greatly appreciated,
Bryan

View 3 Replies View Related

Get Unique Values In A Group Statement

Jul 23, 2006

Hi,
Suppose a table [Inventory]:

Item Color Quantity
-------------------- -------------------- --------------------------
Table Blue 10
Table Red 20
Table Yellow 30
Chair Blue 40
Chair Red 50

I'm wondering if there is a group state like this:
Select Item, ?Function(Color), Sum(Quantity) From Inventory Group by Item
which returns this:


Table Blue,Red,Yellow 60
Chair Blue,Red 90

Does anyone has an idea how this can be achieved?

Regards,
Manolis Perrakis

View 10 Replies View Related

Retrieve When All Values In Group Have Same Record

Feb 25, 2015

Here is some sample data:

CREATE TABLE
#MyTable
(
Pk INT,
GroupID INT,
Value VARCHAR(10)

[code]...

I am looking to retrieve any GroupID in which every Value of that GroupID is either (a) null, (b) an empty string, or (c) "XYZ". So in the above example, GroupID #1 would not be returned in my query because there is a Value of "ABC", but GroupID #2 would be returned since it consists of only nulls, "XYZ"'s, and empty strings.What would be the most efficient way to write such a query?

View 2 Replies View Related

Concatenate List Of Values Under A Group

Aug 4, 2007

I have the following dataset:

State ZIP Homes Schools
WA 98007 2000 4
WA 98052 3000 5
WA 98079 2000 3

Now if I have set the group by expression on State but as display if I want to show it as €œ[98007, 98052, 98079]€? how can I accomplish this.

My report needs to show:
State Homes Schools
[98007, 98052, 98079] 7000 12


Any help will be greatly appreciated

View 6 Replies View Related

Repeate Group Values In Matrix

Jan 22, 2007

Hi,

I am using matrix to make a report. I have company name in the row group and user name in the details field. When I run the report I only see the company name once and each user of that company is displayed in a separate row. Then next company name and its users... I wanted to know if there is a way to display company name next to the user name? I know it can be done by using "table" but I can't use table because in this report there are other fields can only be done in a matrix. So, please let me know if there are any settings in matrix which I can use to display my company name next to each user of that company. Please ask me any thing if the question is not clear. Thanks a lot for the help.

-Rohit

View 7 Replies View Related

Reporting Services :: Concatenating Row Group Values

May 20, 2015

I have row group created here on Due Month & Sales Region & added total after Due Month. When a user clicks on particular amount I would like to send the Sales Region value to the new report as Parameter. So Instead of Total text , I would like to have all the sales regions concatenated and sent to the new report. writing an expression to get the report parameter? I have added the picture of how I want the values to be concatenated , instead of Total . Is this not possible in SSRS?

View 5 Replies View Related

How To Create A Column Group Using Two Field Values?

Mar 11, 2008



Hello Friends,
I am creating a report in which I want to create group column using two field value. Is it possible to do so? We have a requirement in which we are fetching data from two different hierarchy.



A B C D E F G H I J K
L 1 2 3....................4 5
M .............................
N .........................
O .......................
P


The report matrix look like the above one. The elements A,B,C are coming from one hierarchy and D,E,F,G,H,I,J,K are coming from other hierarchy. But i have created one data set to fetch the values for the report. But while creating the column group I am getting both two diff fields so I am not able to use it in single Column group and I want to use only one column group.

Can anybody help me out to solve this issue?

View 1 Replies View Related

What Happens When Autoincrement (auto Increment) Reaches Its Highest (greatest, Last) Value?

Aug 19, 2007

What happens when autoincrement reaches its last value? Does my application crash? Will autoincrement wrap?

Let us assume I figure that my database table will be much smaller than 2^16 records. Since it will be nowhere near the limit, I select smallint (2 bytes wide) as my ID field. I set the seed value to -32,767. I set the increment value to 1. Over the course of actual useage, many records are added and deleted many times. Although I correctly anticipated that the number of records in my database is far less than 65,535, autoincrement has reached 65,535. What will happen next? Ideally I would like autoincrement to wrap and take the next unused value. But does it do that? Or does it freeze at the highest value? What happens?

View 3 Replies View Related

SQL Server 2012 :: How To Group By Values Over None Contiguous Data

Jul 22, 2014

I am trying to generate a list of data such as this

STOCKIDMIN_WKNUMBERMAX_WKNUMBER
654987201310201312
654987201320201326
654987201401201403
321654201313201315
321654201329201332
32165420135020135

From a large set of data similar to this

--CREATE TEMP TABLE
IF OBJECT_ID('tempdb..#TEMP_WK_STOCK') IS NOT NULL DROP TABLE #TEMP_WK_STOCK
CREATE TABLE [#TEMP_WK_STOCK](
[WMNUMBER] [int] NOT NULL,
[STOCKID] [int] NOT NULL)

[Code] ...

returns just 2 rows and misses the fact that the wmNumbers stop and start a few diffrent times. I cant see how to set up the query to bring back the 6 rows i would be expecting it this case, without going to a cursor which i really don't want to.

View 3 Replies View Related

Group By After Outer Join - Getting Duplicate Or Null Values

Oct 18, 2013

I've got 2 tables of towns. I'm using outer join because i need all the town from both tables. However I'm sometimes getting duplicates.

My query

select a.town, b.town
from a
outer join b on a.town = b.town
group by a.town, b.town

How to stop getting null values?

portsmouth null
portsmouth portsmouth
southampton southampton
null southampton
TownA null
null TownB

I'm looking for distinct values like this:

portsmouth portsmouth
southampton southampton
TownA null
null TownB
etc...

View 2 Replies View Related

Reporting Services :: Getting Total Of Group Values In SSRS

Jun 26, 2015

I am trying to build a report using SSRS.I need to retrieve a distinct value from my initial query and place this in the header or group row.The detail lines are hidden but may be expanded(shown).I then have another group row in which I require the sum of all distinct values from my previous group row.To explain pictorially I have the following:

-Scroll right to see the pink squares.Note that the total in the pink square is the sum of the individual var3 values distinct so 10 even when var3 =4 in euro currency.
-I have tried using sum(var5) but this will give the incorrect value as it sums all detail lines not just the distinct values.
-I have tried using another dataset but when referenced the grouping behaviour expected is non existent so where I expect 40 I get 80 i.e. sum disregarding values of var1 and var2 although these are the grouping variables.
-I need it to be dynamic so I am unable to use IIF(...).

If I could get var4 or var6 to be the totals I require I could work with that.I have also tried the following custom code:

Dim public unitLimit as Double
Public Function Getcpvalue(ByVal limit_amount1 AS Double) AS Double
unitLimit = unitLimit+ limit_amount1
return limit_amount1
End Function

[code]...

View 2 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved