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.

 All Forums
 SQL Server 2000 Forums
 SQL Server Development (2000)
 max

Author  Topic 

AskSQLTeam
Ask SQLTeam Question

0 Posts

Posted - 2004-06-29 : 11:43:40
Gert writes "i have a table that looks like

date value nr
20040621 10 apa001
20040603 20 apa001
20040521 20 apa001
20040410 0 apa001
20040620 70 apa022
20040602 30 apa022
20040519 90 apa022
20040401 10 apa022 enz.

i want to create an sql statment that give the sum of the value from the max(date) records and it must be selected from a date to a date.

so when if query between date 19000101 to 20040625 i excpect
20040621 10 apa0001
20040620 70 apa0002 so the sum is 80

so when if query between date 19000101 to 20040615 i excpect
20040603 20 apa0001
20040602 30 apa0002 so the sum is 50

i am only intrested in the sum

Thank for helping
Gert van Wijk"

Seventhnight
Master Smack Fu Yak Hacker

2878 Posts

Posted - 2004-06-29 : 12:30:27
Try this:


Declare @myTable table (myDate nvarchar(8), myVal int, nr nvarchar(10))
Insert Into @myTable values('20040621',10,'apa001')
Insert Into @myTable values('20040603',20,'apa001')
Insert Into @myTable values('20040521',20,'apa001')
Insert Into @myTable values('20040410',0,'apa001')
Insert Into @myTable values('20040620',70,'apa022')
Insert Into @myTable values('20040602',30,'apa022')
Insert Into @myTable values('20040519',90,'apa022')
Insert Into @myTable values('20040401',10,'apa022')


Select * From @myTable

Declare @beginRange nvarchar(8),
@endRange nvarchar(8)

Select @beginRange = '19000101', @endRange = '20040625'

Select sum(myVal) From
(Select myVal=(Select myVal From @myTable Where nr=A.nr and myDate = A.maxDate) From
(Select nr, maxDate = max(myDate) From @myTable Where myDate between @beginRange and @endRange Group By nr) as A
) as Z

Select @beginRange = '19000101', @endRange = '20040615'

Select sum(myVal) From
(Select myVal=(Select myVal From @myTable Where nr=A.nr and myDate = A.maxDate) From
(Select nr, maxDate = max(myDate) From @myTable Where myDate between @beginRange and @endRange Group By nr) as A
) as Z


Corey
Go to Top of Page
   

- Advertisement -