help with query 03-19-10

sql server 2008 sp1

I can't seem to get this query right.  I need a way to read a table
and for each person, show the person's
highest value and the person's last entered value to get a result set
like this

person_id   high    last
-------------    -----     -----
1                 40      20
2                 30      15

here is a sample schema

create table test (person_id int, enter_value int, enter_date
datetime)

insert into test values (1, 30, '2001-01-01')
insert into test values (1, 40, '2002-01-01')
insert into test values (1, 10, '2003-01-01')
insert into test values (1, 20, '2004-01-01')
insert into test values (2, 10, '2008-01-01')
insert into test values (2, 30, '2009-01-01')
insert into test values (2, 15, '2010-01-01')

i used MAX but that only gets me the max but I can't seem to get the
last value along with it
0
Derek
3/19/2010 8:04:53 PM
sqlserver.programming 1873 articles. 0 followers. Follow

4 Replies
598 Views

Similar Articles

[PageSpeed] 24

Here is one method:

SELECT person_id, max_enter_value, enter_value AS last_enter_value
FROM (
SELECT person_id, enter_value, enter_date,
        MAX(enter_value) OVER(PARTITION BY person_id) AS max_enter_value,
        ROW_NUMBER() OVER(PARTITION BY person_id
                          ORDER BY enter_date DESC) AS rk
FROM test) AS T
WHERE rk = 1;

-- 
Plamen Ratchev
http://www.SQLStudio.com
0
Plamen
3/19/2010 8:22:52 PM
On Mar 19, 4:22=A0pm, Plamen Ratchev <Pla...@SQLStudio.com> wrote:
> Here is one method:
>
> SELECT person_id, max_enter_value, enter_value AS last_enter_value
> FROM (
> SELECT person_id, enter_value, enter_date,
> =A0 =A0 =A0 =A0 MAX(enter_value) OVER(PARTITION BY person_id) AS max_ente=
r_value,
> =A0 =A0 =A0 =A0 ROW_NUMBER() OVER(PARTITION BY person_id
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 ORDER BY enter_date D=
ESC) AS rk
> FROM test) AS T
> WHERE rk =3D 1;
>
> --
> Plamen Ratchevhttp://www.SQLStudio.com

NICE!

THANKS!
0
Derek
3/19/2010 8:52:24 PM
another method:

select person_id, MAX(enter_value) as max_enter_value,
	(select top 1 enter_value
	from test t2
	where t1.person_id = t2.person_id order by enter_date desc) as 
last_enter_value

from test t1
group by person_id




"Derek" <gepetto_2000@yahoo.com> wrote in message 
news:a0ffdcb9-6e5c-41a3-b8de-612d66af5779@i25g2000yqm.googlegroups.com...
> sql server 2008 sp1
>
> I can't seem to get this query right.  I need a way to read a table
> and for each person, show the person's
> highest value and the person's last entered value to get a result set
> like this
>
> person_id   high    last
> -------------    -----     -----
> 1                 40      20
> 2                 30      15
>
> here is a sample schema
>
> create table test (person_id int, enter_value int, enter_date
> datetime)
>
> insert into test values (1, 30, '2001-01-01')
> insert into test values (1, 40, '2002-01-01')
> insert into test values (1, 10, '2003-01-01')
> insert into test values (1, 20, '2004-01-01')
> insert into test values (2, 10, '2008-01-01')
> insert into test values (2, 30, '2009-01-01')
> insert into test values (2, 15, '2010-01-01')
>
> i used MAX but that only gets me the max but I can't seem to get the
> last value along with it 

0
alex
3/21/2010 5:16:43 PM
My vote goes to Plamen's solution.

Use of the row_number() and rank() functions was one of the most useful
additions to SQL2005, the only problem with them being that you can't use the
value directly in a where or group clause.  As written, you need to wrap the
result set in a separate select statement.  Personally I would have written
the inner SELECT as a CTE and then selected from the CTE because I think it
makes the code easier to read.

Obiron


alex wrote:
>another method:
>
>select person_id, MAX(enter_value) as max_enter_value,
>	(select top 1 enter_value
>	from test t2
>	where t1.person_id = t2.person_id order by enter_date desc) as 
>last_enter_value
>
>from test t1
>group by person_id
>
>> sql server 2008 sp1
>>
>[quoted text clipped - 23 lines]
>> i used MAX but that only gets me the max but I can't seem to get the
>> last value along with it

-- 
Message posted via SQLMonster.com
http://www.sqlmonster.com/Uwe/Forums.aspx/sql-server-programming/201003/1

0
obiron
3/22/2010 5:13:01 PM
Reply:

Similar Artilces:

sumifs help
I have the following formula. =SUMIFS(Table1[2],$A$11:$A$22,$A38,$B$11:$B$22,$B38) It now needs to be changed to a formula that can handle text instead of numbers. How do i do it? Use Countif instead of Sumif from =SUMIF(Table1[2],$A$11:$A$22,$A38,$B$11:$B$22,$B38) to =CountIF(Table1[2],$A$11:$A$22,$A38,$B$11:$B$22,$B38) Do you really have a function Countifs with an "S" at the end? thie maybe an UDF that needs to be modified. -- joel ------------------------------------------------------------------------ joel's Profile: 229 View this th...

Help !
I need to create a data input screen on excel where multiple users at the same time will use them & input data. This data then needs to be stored as a database as well, where i can use it to understand trends Thank you. and the question is ...? <abrahamsaj@gmail.com> wrote in message news:1132155054.927936.191640@z14g2000cwz.googlegroups.com... >I need to create a data input screen on excel where multiple users > at the same time will use them & input data. > This data then needs to be stored as a database as well, where i can > use it to understand trends >...

MS Query variable
Is it possible to pass a variable to an MS query from and excel spreadsheet. ie. can the user enter something into a cell on sheet1 and this be called into an MSquery and the query run on this info? Dean This is certainly possible. However the MSquery results must be returned to excel. You need to access the query properties (right click in the data returned area) and select the Parameters option. This menu option is sensitive to the fact that the query is expecting parameters so ensure that the query is constructed for this first. (MSQuery help hsows you how) Then it is simply a m...

Help with this thing
It was working in the window "Transactions >> Sales >> Transactions of Sales", but exactly were publishing a Quotation, which i wanna print, more nevertheless was shut up to me network, then I closed the window and it threw several messages to me of error, and from that then it was blocked the quotation that was working. My question is as I can unblock this document? ...

Help with Outlook Setup!!!
I have XP Professional installed and Office XP Professional. I have several users setup for kids, as well as my admin account. I want to setup a Limited Account in addition to the Admin account for myself for daily use. Am I just suppose to pick a different account name and login password and then setup my MSN Messenger and Outlook POP email with same username and password that I used to setup the Admin account? I don't need to share any contacts or anything, I just setup the admin email in order to setup Outlook. I want to input my contact info etc., into the Limited account and use ...

HELP !!! I have a ARRAY Formula HELP !!!
Hello, Here is the ARRAY Formula I have and this is what I am using it for. The situation is that it worked 1 time and than not again. =INDEX(D48:K48,,MAX(IF(D48:K48<>"",COLUMN(D48:K48)))-COLUMN(D48)+1 Duty: I have a row of number that appear hourly (DOLLAR AMOUNTS), the numbe are anything from nothing to 10000. I want the hourly number to appea in specified cell. Here is an example. (I am using EXCEL 2000) Row D48:K48 answer in cell G2 1st hour D48 = $100.00 G2 Should be $100.00 2nd Hour D48 = $100.00 E48 = (nothing) G2 Should be (nothing) 3rd Hour D48 = $1...

Use Outlook to send to contacts in a query
Is there a way to set Outlook to send to contacts stored in a query (or a table) WITHOUT just importing them and doing it that way? I want to create a database, set Outlook to look in it, and have it send to contacts whose contact information will be listed in that database. Alan: Yes, there is a way. But have you explored, and rejected, storing contacts in Outlook and creating Outlook Distribution Lists? If you really need to store your contacts in Access, then you could use VBA code in your Access database to start Outlook and send and an email (or Mailitem as Outlook calls it). Y...

exch 5.5 help
I am in a progress to upgrade Exchange 5.5 (on NT4) to Exhange 2k3 (on 2k3). I setup a test machine and upgrade the OS to w2k3. 1st I want to connect the 5.5 to AD, so I should install ADC. Can anyone tell me the steps? Frorestprep, domainprep, setup adc, and upgrade to exchange 2k3? If you run through the steps in the E2K3 deployment tools they will walk you through everything. -- Hope that helps. ------------------------- Jaclynn Hiranaka Enterprise Messaging Support This posting is provided "AS IS" with no warranties, and confers no rights. � 2004 Microsoft Corporation. Al...

Help with Formula Please 02-19-10
Need a Formula for the following: Data Table A B C D E F G H I 1 Tom A W 2 H 30 84 30 2 Peter A W 3 H 3 Nick B L 1 A 70 Columns F1:I3 from Data Table has break scores for each player. Below is the Result Table where I need to show a summary report for high breaks. I have no problem with Break as I use the Large function. I need a formula to insert in A1 and A2 to place the name for the corresponding breaks below. Result Table High Breaks A B Name Break 1 ...

help...help...help
I just installed Microsoft Office XP Professionaql with no problem. However, whenever I try to perform any task such as opening contacts area in order to create an entry, I receive a dialog box with Microsoft Outlook and a yellow exclamation point. Also, included in the dialog box are the words could not open the item, try again. Other information that might be important is that I use a pst file. The error message also occurs when I try to open the Contact folder from the folder list as well as when I try to perform any function. It was a clean install not an upgrade. Could you ...

Need help in data copying.
Hi I have an invoicing file in excel (Sheet1). I need to store the dat which is invoiced into another sheet. My Invoice Data starting from Ro 8 and column B to F (The first item is from B8-F8, second item i B9-F9). B-Item Code, C-Item Name, D-Qty, E-Price, F-Total. Once I print the invoice, I need to transfer the data to another shee (Sheet2) . When I create another invoice, the new data should be added below t the previous data in Sheet2. So that I can have all the items I sol in Sheet2. Can someone help me sending a macro for it??? I will be grateful to you. Thanks in advance Tom -...

Macro Help
Hi, I had alot of help yesterday from Jacob with the following macro, but am getting a 'run time error 13' when trying to run the macro, and i cannot see why. Any help much appreciated Sub OLApp() Dim objOL As Object, objApp As Object, lngRow As Long Set objOL = CreateObject("Outlook.Application") For lngRow = 9 To Cells(Rows.Count, "A").End(xlUp).Row If Range("E" & lngRow) = "" Then Set objApp = objOL.CreateItem(1) With objApp ..Subject = "Change Password for system" & Range("A" & lngRow)...

help me #2
how to restrict entering of same values or data in excel cell Hi if you mean the 'preventing of duplicate entries' you may check the following site http://www.cpearson.com/excel/NoDupEntry.htm -- Regards Frank Kabel Frankfurt, Germany mangesh khati wrote: > how to restrict entering of same values or data in excel > cell ...

Problem with LeadTools CreateWindow inCFormView -Help !!!
Hi , I have been using LeadTools in Visual Studio 2005. I have a tabctrl and dialogs in each tab and developed using CFormView. So a tabCtrl is a child of CFromView and tab1 is a child of TabCtrl. I want to insert a LEAD control in one of the tabs .i.e, Dialog.I am unable to insert a leadcontrol but inserting a control in the view was easy.The problem is I am not able to get the HWND associated to a particular dialog which is super child of View. Can somebody help me in creating a lead control in the dialog configdlg .h LAnnotationWindow m_LAnnoWnd; FormView.cpp CMyTabCtrl m_myCtrlTab; ...

Query to Count "0" in Row
I am trying to create an expression in a query that says if CONTRIBUTION BEGIN year is less then 2006 and the AUTE2 = 00/00/00 then count the number of "0" in the rown and multiply that by 58. This is what I had thought up so far, but I know it isn't right. CONTRIBUTION DUE: IIF([CONTRIBUTION BEGIN], 'yyyy' <2006, AND AUTE2 = 00/00/00, Count "0" And Multiply by 58 Any input is greatly appreciated. -Anthony Morano What kind of data type is being stored in your [AUTE2] field? If that is supposed to be a date, I don't think Access considers #00/00/00...

CString help
I'm looking at a website on CString Management: http://www.codeproject.com:80/string/cstringmgmt.asp In the section entitled, "CString to char * II: Using GetBuffer," the author stresses calling ReleaseBuffer after calling GetBuffer. Is this always necessary? I often use CString::GetBuffer when using CStrings in MessageBox dialogs like so: MessageBox(m_hWnd, cString.GetBuffer(0), lpTitle, MB_OK); Should I be adding a ReleaseBuffer after a MessageBox call? Should I be passing my string data to the MessageBox in another way? Regards, Joe > Is this always necessary?...

HelpProvider and HTML Help interaction
I have an application with a .chm help-file. But I have some questions about the behaviour of the help-window. I use a modal application window and I can start the help. The help windows appears but it is allways in foreground of my application window. I can set the input focus on my window, the help window becomes inactive but I cannot move my window over the help window. So I have to close the help window or minimize it or move it aside of my application window when I want to go on in my application. The other problem is when I minimize the help window and then open a dialog...

Your Help is Appreciated
Dear all I am using MS Excel 2003 and I am trying to plot a graph/chart/graphical representation of the following: I would like to somehow plot : Time Price Meetings 16/09/2002 23/09/2002 225 27-Sep-02 30/09/2002 07/10/2002 14/10/2002 368 21/10/2002 23-Oct-02 28/10/2002 04/11/2002 354 11/11/2002 18/11/2002 235 25/11/2002 02/12/2002 I dont mind how the data is displayed but I envisaged some kind of bar chart to represent the prices and a line chart / crosses to indicate the dates of the meetings. Can anyone help with this or am I being stupid? Thanks for everything i...

OLE DB Query in Excel
Is it possible to pass parameters to SQL in an OLE DB query within Excel. For example: Select * from property where prop_id = ? Somehow link the parameter to a cell in the spreadsheet or something in like. Thanks. Hi Joe, You can link parameters from your spreadsheet to SQL statements but right off hand I can't remember if you need to do this with a VBA SQL line or you can imbed it directly in an SQL statement. Could you show us the SQL statement or VBA SQL line. -- Thanks, Shane Devenshire "JOE OROZCO" wrote: > Is it possible to pass parameters to SQL in an OLE...

Money-Changing Account number to handle Vanguard changes
Hi: Vanguard has changed the account numbers for its brokerage accounts. This has caused money to download brand new accounts with nothing in them and stop updating my old account numbered accounts. I changed the account numbers in Account Detail page but still not working. Anyone who has any info on what I'm missing please pass along. I cannot lose years and years of past data by just switching to the newly downloaded accounts. Greg PS: Microsoft Money Plus Premium, most recent version On the old accounts, turn off on-line updates. You should then be able to merge the old accoun...

bcc help
can't seem to send mail to bcc? I copied e-mail addresses from an excel spreadsheet and pasted the into the bcc header. I made sure there was coma between each. I entered the form letter and "from" and "to" and "subject" fields an sent the mail. The "to" received the mail but the bcc did NOT receive the mail. What did I do wrong ----------------------------------------------- ~~ Message posted from http://www.ExcelTip.com ~~View and post usenet messages directly from http://www.ExcelForum.com ...

Visual Studio Tools for Dynamics GP 10.0
Hi, Is the latest release of Visual Studio Tools for Dynamics GP 10.0, compatible with Visual Studio 2008? -- Regards, Vaidy The latest version of Visual Studio Tools shipped with the GP 10.0 Feature Pack. That version is compatible with Visual Studio 2008. Projects created with earlier versions of Visual Studo Tools can be upgraded to work with VS 2008. However, to install the VS Tools templates into Visual Studio 2008, you must be using the VS Tools version that shipped with the 10.0 Feature Pack. -- This posting is provided "AS IS" with no warranties, and confers ...

Comparing queries
Hi, I am using a database storing equipment for rooms where I have two queries set up, one listing original equipment and another listing current equipment for room layouts. The two queries work fine independantly, but I now want to compare differences between these where I need to know: 1 - equipment in both original and current rooms. 2 - equipment in original room now missing from current room. 3 - equipment in current room, not required in original room. Regards, Dave. You did not say anything about the table structure so I will go with what you posted. Use a unio...

Rules Wizard Help
I have a rule in the Rules Wizard that forwards on an email to distribution list that is received from a certain person. I would like to have a rule that forwards on this email, but I woul like to forward it with some set text as well. For example, the email shows after being forwarded by the rule: > ---------- > From: Person1 > Sent: Friday, February 20, 2004 6:52:37 AM > To: DistributionList > Subject: DISCOVERER SHOULD NOW BE AVAILABLE > Auto forwarded by a Rule > > DISCOVERER SHOULD NOW BE AVAILABLE However, after I would like it to forward some text as ...

More help with formula
I need 2 formulas for the following: Problem 1: Columns "c" thru "g" contain numbers from 1 thru 100. If th numbers is those columns are 50 or less then I the sum to go in on column; then the sum of numbers between 51 to 100 to go into anothe column. Problem 2: Columns "c" thru "g" contain numbers from 1 thru 100. If th individual number 1-100 is used (3 times, 4 times, 5 times, etc.) tota the I need to show the number of times it was used in the columns. For example: If 1 is used 5 times in columns C thru G then the numbe is 5; the same with 2, th...