T-SQL (SS2K8) :: Selecting Latest Record With Info

Aug 27, 2014

I have created the following SQL snippet that is a very simple mock-up illustrating the problem (I hope!) that I am facing:

-- create table
if object_id('tempdb..#tmpdelnotes') is not null
drop table #tmpdelnotes

create table #tmpdelnotes(
DelNote int identity (1,1) ,
DelDate date not null,
Item int not null,
Customer int not null)

[code]...

What I need to retrieve is a unique list of item numbers with information about the latest (DelDate) delivery note. The "Clumsy workaround" works, but is not very pretty when doing multiple table joins. Is it really necessary to use a derived table for this kind of query? Window functions can only exist in the SELECT and ORDER BY clauses, which is understandable since the calculations take place (I would guess) after the aggregations in the HAVING clause.

View 2 Replies


ADVERTISEMENT

T-SQL (SS2K8) :: Selecting The Top Record With Certain Conditions?

May 14, 2014

The situation is that we have resources (trucks) that perform shifts. Shifts consists of actions. A resource can perform multiple shifts.

For every resource we want to find the record that:

- Is 'younger' than the last realized action.

- Has actionkind pickup, deliver or clean

I have constructed a solution with CTE and row_number but I was curious if there would be other alternatives. The fact that I'm joining a CTE onto itself and subject the outcome to a partition makes me think there are sharper ways.

Note that the action id in the data below is also sorted but in practice this need not be the case. The sorting key is prevalent.

output of the query is

id_action id_resource actionKindCode
4665 4 clean
34540 96 pickup
24000 901 clean
declare @mytable table (
id_action int,
id_shift int,

[code]....

View 6 Replies View Related

Query The Latest Info

Jan 6, 2005

Hi All,

I have thsi list of record

Chasis Status Date
pl1 sold 10/20/2004
pl1 return 10/21/2004
pl2 sold 10/24/2004
pl2 return 10/25/2004
pl3 sold 11/01/2004
pl4 sold 11/03/2004
pl4 return 11/04/2004
pl4 sold 11/06/2004


sp i want to list out cars that status solid has been sold

so in this case only pl3 and pl4 can be display. So anyone can advise me on this. thanks

Regards,
Shaffiq

View 6 Replies View Related

Selecting Latest Date

May 8, 2008

Hello all. I ma using the following query to pull back data. The MergeHistory table has a column named DateMerged. I am looking to pull back the one record with the most recent DateMerged. I have managed to get the query as far as below but not sure how to select the most recent one. Can anyone help with this? I was told it may be along the line of SELECT TOP 1 or something?


INSERT INTO @List (IndexID, IndexName, MergeSystem, Status, DateCreated, CreatedBy, DataTag, MergedDate)
SELECT DISTINCT
RT.IndexId,
isnull(dbo.ufn_GetBestIdentifier(RT.IndexId), dbo.ufn_GetBestVirtualIdentifier(RT.IndexId)),
dbo.ufn_GetEntitySystemName(RT.IndexId),
RT.Status,
CONVERT(varchar, RT.DateCreated, 106) as DateCreated,
RT.CreatedBy,
RT.DataTag,
MH.MergedDate
FROM @resulttable AS RT, MergeHistory AS MH
WHERE RT.IndexId = MH.EntityID

View 4 Replies View Related

Selecting Latest Version.

Feb 11, 2008

Hi everybody!

I am developing realese system. It contains application, application releases and changes that have been made in a particular release.

What i need to do is: I need to retrieve the latest version for a particular application and the latest change so as a result I would see in a table:
application, latest version and latest change for the latest version.

I tried to querry that using Max function but it does not seem to work as I get e.g. 2 rows when there are 2 records for the same version.

Could anyone help me?

View 13 Replies View Related

Selecting The Latest Date From Different Columns

Jul 20, 2005

I have 6 columns, all with dates within them, i.e.Proposed Start Date 1Proposed Start Date 2Proposed Start Date 3Proposed Finish Date 1Proposed Finish Date 2Proposed Finish Date 3What I need to do is narrow this down into two fields:Start DateFinish DateSo I need to find the newest value from the columns. i.e.If PS1 filled PS2 and PS3 empty, then Start Date = PS1If PS3 empty and PS2 filled, then Start Date = PS2If PS3 filled then PS3and similarly for Proposed Finish Dates.Anyone knew how I can do this.(Maybe the following will help for the programmers out there:If PS3 <> nullThen StartDate = PS3Else if PS2 <> nullThen StartDate = PS2ElseStartDate = PS1End IFJagdip

View 5 Replies View Related

SQL Server 2012 :: Query Pulling Latest Info Data From Table

Aug 29, 2014

Let's say I have a table of data as per the below..

I'm trying to extract only the green highlighted items..

The rules applied are: Only the latest data concerning all cases, and only 1 line (the latest) per case.

As you can see in the image, I don't want the 2nd,3rd, and 4th record extracted cause they are all superseded by more recent records (identified as they are further in the table).

I've considered using either Distinct or Having? but can't get that to work.. If I could use Distinct but then ensure it's the latest record in the table that would be perfect.

View 7 Replies View Related

T-SQL (SS2K8) :: Latest Comment Per ID

Jul 30, 2015

I want to get the latest comment for each id based on the maximum createdDate and not sure how to do this, tried to do Max but it was still returning all the rows.

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Audit](
[id] [nvarchar](64) NOT NULL,

[Code] ....

View 2 Replies View Related

Latest Record

Sep 20, 2007

My table are
Customer: customerId ,name
Order: orderId, customerId, product,date
I want to display latest order  from the customer
 
 
 

View 2 Replies View Related

Latest Record For Particular ID

Jan 24, 2014

I have table has column called [last modified date] it has time too , i need to get the [latest modified date] for particular ID , there are many updates to the ID and i just need the latest date.

[PAX ID] | [Last Modified Date]
1 2013-01-02 18:23:00
1 2013-01-02 11:42:00
3 2013-01-01 09:00:00
3 2013-01-08 16:05:00
5 2013-01-01 09:09:00

View 2 Replies View Related

Get Record With Latest Date

Jun 4, 2007

 if there are 2 records with different date  how to write query for ----> get record with latest date 

View 4 Replies View Related

Group By And Latest Record

Aug 8, 2013

Here's what I'm trying to do

TransIDMemberIDFundIDBuyPriceDate
1501101$1042013-01-24
2501102$1012013-04-23
3501102$1182013-02-04
4501102$982013-05-19
5501103$532013-05-21
6501103$392013-07-09

I'm trying to get the latest buy price for each fund a member bought.

So in the above example, I'm trying to formulate a query to retrieve all the latest bought price for memberid 105:

Desire Query Result

TransIDMemberIDFundIDBuyPriceDate
1501101$1042013-01-24
4501102$982013-05-19
6501103$392013-07-09

So far, I've tried using Group By clause on FundID and BuyPrice and MAX() function for the date, but I can' get the TransID.

View 3 Replies View Related

How To Get Latest Date Record

Apr 10, 2014

I want to get latest updated date on each transid and only for status =approved .

-------------------
out put would be
------------
idtransid date status
31013/1/2014 approved
61031/2/2014 approved

table
-----------
idtransid date status
11011/1/2014 approved
21012/1/2014 close
31013/1/2014 approved
41021/2/2014 approved
51022/2/2014 close
61031/2/2014 approved

View 1 Replies View Related

Conditions On Latest Record

May 18, 2006

I have a table that has records layed out as so:Table:fd_Id INT IDENTITY (1, 1)fd_User VARCHAR(30)fd_Effective DATETIMEData could be as follows:1 | "user1" | 6/20/20012 | "user2" | 6/1/20023 | "user2" | 6/5/20024 | "user2" | 6/5/20025 | "user2" | 2/1/20026 | "user3" | 9/1/20037 | "user3" | 10/2/20028 | "user4" | 1/1/2005What I need to retrieve from that table is the SINGLE LATEST item ofeach fd_User.Results:1 | "user1" | 6/20/20013 | "user2" | 6/5/2002 (or 4 | "user2" | 6/5/2002) since the dates arethe same but only 1 of them6 | "user3" | 9/1/20038 | "user4" | 1/1/2005

View 3 Replies View Related

Get Record With Latest DateTime

Oct 1, 2007



Hi,

Can anyone please let me know the query to get the latest record based on datetime cloumn?
For example, a table with three records:

Name | Application | Start Time

User A | Outlook | 10/01/2007 1:30 AM
User A | Internet Explorer | 10/02/2007 12:30 AM
User B | Internet Explorer | 9/20/2007 8:30 PM

The query gets the below:

User A | Outlook | 10/01/2007 1:30 AM
User B | Internet Explorer | 9/20/2007 8:30 PM

Thanks in advance.

View 1 Replies View Related

Query To Fetch Latest Record

Jun 29, 2012

Table has details like below:

NAME UPATE-TIMESTAMP
==== ===============
mary time1
mary time2
mary time3
tom time1
tom time2
tom time3
tom time4
richard time1
richard time2

Output Expected:

NAME UPATE-TIMESTAMP
==== ===============
mary time3
tom time4
richard time2

In summary, the requirement is to fetch the latest upated record for each unique NAME.

View 1 Replies View Related

Latest Record For Each Reference Field

Feb 19, 2014

I have a table that contains a Ref field and a TransactionDate field. For each Ref field there are mutliple Transactions. I am trying to put together a query that selects the Latest Transaction date for each Ref field in the table.

I tried:

SELECT *
FROM tabMediaTransaction
WHERE (TransactionDate =
(SELECT MAX(TransactionDate) AS Expr1
FROM tabMediaTransaction AS tabMediaTransaction_1))

But this only returns 1 record for 1 Ref field. I need 1 record for each Ref field

View 7 Replies View Related

Unable To Get Latest Date Record?

Apr 10, 2014

i want to get latest updated date on each transid and only for status =approved .

-------------------
out put would be
------------
idtransid date status
31013/1/2014 approved
61031/2/2014 approved
table
-----------

idtransid date status
11011/1/2014 approved
21012/1/2014 close
31013/1/2014 approved
41021/2/2014 approved
51022/2/2014 close
61031/2/2014 approved

View 2 Replies View Related

T-SQL (SS2K8) :: Return Value In A Status Field Which Has Latest Year And Month

May 11, 2015

I have table in which month & year are stored, Like this

Month Year
10 2014
11 2014
12 2014
1 2015
2 2015
3 2015
4 2015

I wanted a query in which it should return the value in a status field which has latest year & month.

View 9 Replies View Related

Transact SQL :: Retrieve Latest Record Of Serial Number With Multiple Entries

Sep 30, 2015

I work for an organization that repairs serialized devices. Each time a device is repaired it's serial number is recorded in a database table along with the date it was repaired along with other information about the device. There are multiple cases where a unit has been repaired more than once.

I am trying to write a query that will return the serial only once and that record will be the record of the latest repair date. To sum it up,

Return a list of serials where if a serial exists more than once in the table, return only the instance of the serial record(s) with the max(created_dt). The end result will be a list of distinct serial numbers.

Here is my Query. The problem I believe is in my sub-query but I am not sure how to structure it.

SELECT
S.Id
, RMA
, PinSerial
, L4Serial
, L4Model

[Code] ....

View 3 Replies View Related

Transact SQL :: Selecting Latest Date But Over Another Date Column Including Nulls?

Nov 26, 2015

CREATE TABLE #Dateissue
(ID int,
Code nvarchar (20),
Datein datetime,
Declined datetime )

[Code] .....

I have a table here.  I want  find a way of getting the latest date, when the code is the same.  If the Declined date is null.  Then I still want the latest date.  E.g. ID 3.  

If the declined date is filled in.  Then I want to get the row, when the Datein column value is greater then the declined date only.

I tried grouping it by max date, but   i got an error message when trying this out.  Against the code  

WHERE MAX(Datein) > Declined

An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.  What do I need to do to get both my outputs working? 

View 9 Replies View Related

Selecting Record

Sep 4, 2007

Hi i was wanting to know how to select a record in a gridview. I have a gridview with firsname and lastname. I currently have select command on it but don't want it. I want to be able to select first name or last name and have it take me to that record on the database.  

View 3 Replies View Related

T-SQL (SS2K8) :: Selecting Top 1 From Multiple Ranges?

Mar 28, 2014

I have data like the following:

ID COUNTER DATA
1 10 BLAH
1 20 BLAH
2 10 BLAH
3 10 BLAH
2 20 BLAH
2 30 BLAH

What I want to return is:

1 20 BLAH
2 30 BLAH
3 10 BLAH

I want the top 1, having the highest counter from each ID. This is a highly simplified version of that I am pulling which also is between a date range, but same principle.

IE: SELECT * FROM Table WHERE ID in (SELECT DISTINCT ID FROM Table WHERE Date BETWEEN <date> AND <date>

I'd rather keep it in one statement if possible, but if I have to do it in multiple passes then so be it.

View 6 Replies View Related

T-SQL (SS2K8) :: Selecting From A Remote Spreadsheet

Jun 11, 2014

I'm trying to run this code, which worked on SQL 2000, on 2K8:

SELECT [Business Unit]
,[Department]
,[Ext :]
,[F9]
,[First Name :]
,[Last Name :]
,[Mobex :]
,[Mobile :]
,[Sub Department]
FROM MyCompanyStaffPhoneList...Sheet1$

However it just returns this message..Msg 7308, Level 16, State 1, Line 1 OLE DB provider 'Microsoft.Jet.OLEDB.4.0' cannot be used for distributed queries because the provider is configured to run in single-threaded apartment mode.

View 2 Replies View Related

T-SQL (SS2K8) :: Selecting Text Between Set Characters

Nov 2, 2015

I have a table of data with lines of various lengths. An example is

A Smith - Give #12345# Sydney City
B Jones and S Jones - Give #876543# Washington

I am trying to work out how to create a new column with just the number between the # symbols. The number would be between 5 and 9 numbers.

View 9 Replies View Related

Get 1 Record Out Of SQL Express And Use Info In &<head&> And &<body&> Areas, Not In A Grid.

Jan 1, 2008

 Hi
Just started using Visual Studio Express 2005 (Web) with Server 2005 Express and I am trying to extract the data from a SQL but cannot find how to connect to and open a SQL recordset so as to use the values of a single record dotted around a page.  I would be using the values in the <Head> and <body> areas of the page.  The body of the page would utilise standard data grids for sub and sub data, this being no problem.
Below is how I would have retrieved the "EndDate" value from an Access databse under asp.

 Set Conn=Server.CreateObject("ADODB.Connection") Set rs=Server.CreateObject("ADODB.RecordSet") Conn.Open "DBQ=" & Server.MapPath("../private/Drapers.mdb") & ";Driver={Microsoft Access Driver (*.mdb)};"   rs.open "SELECT * FROM Products where ID = 44", Conn, 3, 3     rs("Metta1") rs("Metta2")
The following is from the Web.config file

<connectionStrings><add name="ConnectCB" connectionString="Data Source=.SQLEXPRESS;AttachDbFilename=|DataDirectory|CBBasic.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/></connectionStrings>
I have tried lots of things that were either code that was superceeded  or just plainly didn't work.
Any help would be appreciated.
      John

View 3 Replies View Related

T-SQL (SS2K8) :: Unable To Extract Data Based On Matching Info From A Local Database

Oct 2, 2014

I have a MySql Database i need to extract data from based on matching info in a local SQL Server database,

I will ultimately need to cycle through 20 of these MySql databases , but the query below is taking 1 minute and 20 plus seconds...Just for one..

Is there a simple tweak that would speed it up?

USE [CAS]
GO
DECLARE @PhoneDB varchar(max),
@SQL NVARCHAR(MAX);
set @PhoneDB = '[PHONEDB_PHI]';
set @SQL = 'SELECT

[Code]....

View 4 Replies View Related

T-SQL (SS2K8) :: Table With Score Info For Groups - Ranking For Current And Previous Week

Jan 21, 2015

I have a table with score info for each group, and the table also contains historical data, I need to get the ranking for the current week and previous week, here is what I did and the result is apparently wrong:

select CurRank = row_number() OVER (ORDER BY cr.CurScore desc) , cr.group_name,cr.CurScore
, lastWeek.PreRank, lastWeek.group_name,lastWeek.PreScore
from
(select group_name,
Avg(case when datediff(day, asAtDate, getdate()) <= 7 then sumscore else 0 end) as CurScore

[Code] ....

The query consists two parts: from current week and previous week respectively. Each part returns correct result, the final merged result is wrong.

View 3 Replies View Related

Selecting Next And Previous Record

Jun 25, 2004

I'm trying to add a next and previous button to a popup window I have on a photo gallery -

Having trouble with the sql

I know I would have 2 select statements that would each return 1 result set.

I know how to get the top ( and bottom by ordering descending and doing Select Top 1)

But how would I get the next one up!

I would hate returning the entire image section and perform the calcuation in the business tier :(

View 4 Replies View Related

Selecting The First Record In A Join?

Mar 1, 2012

I have one table like this:

Code:
CREATE TABLE DlIndexTable
(SessionStartTime DATETIME NOT NULL PRIMARY KEY, SchemaID INTEGER NOT NULL,
DLBaseRate REAL NOT NULL)

and one like so:

Code:
CREATE TABLE DlTextDataTable (
SessionStartTime DATETIME NOT NULL REFERENCES DlIndexTable,
ChTimestamp FLOAT NOT NULL, Channel01data VARCHAR (255),
Channel02data VARCHAR (255), ... , Channel16data VARCHAR (255),
CONSTRAINT TxtDatPriKey PRIMARY KEY (SessionStartTime, ChTimestamp))

I want to get some combined data from both tables, so right now I am joining them at the SessionStartTime column, which is a primary key in the first and a foreign key in the second table, something like this:

Code:
SELECT DlIndexTable.SessionStartTime, DlTextDataTable.Channel01data
FROM DlIndexTable
LEFT JOIN DlTextDataTable
ON DlIndexTable.SessionStartTime = DlTextDataTable.SessionStartTime
WHERE DlIndexTable.SessionStartTime BETWEEN '2006-10-13 16:40:08.790' AND '2012-03-01 17:54:30.930'
ORDER BY DlIndexTable.SessionStartTime, DlTextDataTable.ChTimestamp

The trouble is that this query, exactly as requested, gives me all the entries from the second table matching the first, while I really would like to pick just one row (preferably, the first chronologically - by ChTimestamp) so that the first column (SessionStartTime) has distinct entries in the resulting table. What would be the simplest way of doing that? Performance is not a big priority over simplicity since the first table could have only a few hundred rows (maybe a couple of thousand), while the second will be real tiny.

View 10 Replies View Related

Selecting Top Record In A Group?

Mar 18, 2015

I’m writing a document management system. The documents themselves are created from the contents of a database. The database is SQL Server.

The database contains a table, like so:

ClientID, ProjectID, DocumentID, MinorVersion, MajorVersion, Name

Initially, the user will create a “V0.1” document. So the data would look something like

ClientID = 1
ProjectID = 1
DocumentID = 1
MajorVersion = 0
MinorVersion = 1
Name = “My Document”

Thereafter, the user can create new versions as “0.2”, “0.3”, etc., or “1.0”, “1.1”, “2.0”, etc.

For example, a “2.1” document would be stored as:

ClientID = 1
ProjectID = 1
DocumentID = 1
MajorVersion = 2
MinorVersion = 1
Name = “My Document”

The earlier versions will still exist on the database, but the latest version will be 2.1.

There may be several different documents, with different DocumentID’s (e.g. DocumentID = “1”, DocumentID = “2”), etc., and each of these documents may have many versions.

I’m trying to write a query to display a list of documents showing ClientID, ProjectID, DocumentID, MinorVersion, MajorVersion, Name… but the list should only display the latest version of each document.

So, if the database contained the following records:

ClientID, ProjectID, DocumentID, MajorVersion, MinorVersion, Name
1,1,1,0,1,My Document
1,1,1,0,2,My Document
1,1,1,0,3,My Document
1,1,1,1,0,My Document
1,1,1,2,0,My Document
1,1,1,2,1,My Document
1,1,2,0,1,My Second Document
1,1,2,0,2,My Second Document
1,1,2,0,3,My Second Document

My query should return:

ClientID, ProjectID, DocumentID, MajorVersion, MinorVersion, Name
1,1,1,2,1,My Document
1,1,2,0,3,My Document

… where 2.1 is the latest version of Document 1 and 0.3 is the latest version of Document 2.how to do it.

View 4 Replies View Related

Selecting Most Recent Record

Jul 20, 2005

MSSQL2000I have a table that contains customer transactionsCustomerIDTransactionTransactionDate....I need to select the most recent record that matches a specific CustomerID.I am fairly new to SQL, could someone provide a sample select statement.TIATim Morrison-- Tim Morrison--------------------------------------------------------------------------------Vehicle Web Studio - The easiest way to create and maintain your vehicle related website.http://www.vehiclewebstudio.com

View 3 Replies View Related

Selecting Unique Record

Jul 20, 2005

I have a stored procedure (below), that is supposeto get a Reg Number from a table, (Reg_Number), insuch a way that every time the stored procedure is called,it will get a different reg number, even if the storedprocedure is called simultaneously from two differentplaces,However it is not working that way.If two different users access a function in thereVB program at the same time, the two different userswill get the same reg number.I have looked at the stored procedure, it looks foolproof,yet it is not working that way.Thanks in Advance,Laurence NuttallProgrammer Analyst IIIUCLA - Division of Continuing Education'---------------------------------------------------------------------------Here it is:CREATE PROCEDURE sp_GetNextRegNum@newRegNum char(6) = NULL OUTPUTASLABEL_GET_ANOTHER_REG:Select @newRegNum =(select min(Reg) from reg_number)IF Exists (select Reg from reg_number where reg = @newRegNum )BeginDelete from reg_number where reg = @newRegNumIF @@Error <> 0BeginGoto LABEL_GET_ANOTHER_REGEnd--EndifEndELSEGoTo LABEL_GET_ANOTHER_REG--EndifGO

View 6 Replies View Related







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