Help With An MS SQL Server Query To Return The Latest Dates Against Each RecordID.
Jul 20, 2005
The following SQL query :-
SELECT CardHolder.RecordID, History.GenTime, History.Link1
FROM History FULL OUTER JOIN
Card ON History.Param3 =
LTRIM(RTRIM(Card.CardNumber)) FULL OUTER JOIN
CardHolder ON Card.CardHolderID =
CardHolder.RecordID
WHERE (Card.Deleted = 0) AND (History.GenTime IS NOT NULL)
ORDER BY CardHolder.RecordID, History.GenTime DESC
I have a SQL query I need to design to select name and email addressesfor policies that are due and not renewed in a given time period. Theproblem is, the database keeps the information for every renewal inthe history of the policyholder.The information is in 2 tables, policy and customer, which share thecustid data. The polno changes with every renewal Renewals in 2004would be D, 2005 S, and 2006 L. polexpdates for a given customer couldbe 2007-03-21, 2006-03-21, 2005-03-21, and 2004-09-21, with polno of1234 (original policy), 1234D (renewal in 2004), 1234S (renewal in2005), and 1235L (renewed in 2006).The policy is identified in trantype as either 'rwl' for renewal, or'nbs' for new business.The policies would have poleffdates of 2004-03-21 (original 6 monthpolicy) 2004-09-21 (first 6 month renewal) , 2005-03-21 (2nd renewal,1 year), 2006-03-21(3rd renewal, 1 yr).I want ONLY THE LATEST information, and keep getting earlyinformation.My current query structure is:select c.lastname, c.email, p.polno, p.polexpdatefrom policy p, customer cwhere p.polid = c.polidand p.polexpdate between '2006-03-01 and 2006-03-31and p.polno like '1234%s'and p.trantype like 'rwl'and c.email is not nullunionselect c.lastname, c.email, p.polno, p.polexpdatefrom policy p, customer cwhere p.polid = c.polidand p.polexpdate between '2006-03-01 and 2006-03-31and p.polno like '1234%'and p.trantype like 'nbs'and c.email is not nullHow do I make this query give me ONLY the polno 123%, or 123%Sinformation, and not give me the information on policies that ALSOhave 123%L policies, and/ or renewal dates after 2006-03-31?Adding a 'and not polexpdate > 2006-03-31' does not work.I am working with SQL SERVER 2003. Was using SQL Server 7, but foundit was too restrictive, and I had a valid 2003 licence, so I upgraded,and still could not do it (after updating the syntax - things likeusing single quotes instead of double, etc)I keep getting those policies that were due in the stated range andHAVE been renewed as well as those which have not. I need to get onlythose which have NOT been renewed, and I cannot modify the database inany way.*** Free account sponsored by SecureIX.com ****** Encrypt your Internet usage with a free VPN account from http://www.SecureIX.com ***
i want a query which returns all the date between 2 dates . its like an calender.....for example i selected 2-1-2006(dd-mm-yyyy) to 18-03-2006 ....it should returns like this 2-1-2006 3-1-2006 4-1-2006 . . . 16-03-2006 17-03-2006 18-03-2006
why the statement "where WD.WRKD_WORK_DATE BETWEEN DATEADD(DD, -6, GETDATE()) AND GETDATE()) = 0' is successful, but "WD.WRKD_WORK_DATE BETWEEN (DATEADD(DD, -16, GETDATE())) AND (DATEADD(DD, -3, GETDATE()))" is an invalid statement? I've tried a lot of different syntax variations of this statement and cannot get to work between two lookback dates.
Here is my SQL Query. The Table where the data is coming from has 19,000 rows of data however, this only returns 2550 rows of data.
In the where statment I am call all the select tables, with the OrbitimportId that is most recent. But it only returns 2500. I need help retirenving the entire liste with the most recent OrbitimportId.
Help!
SELECT TOP (100) PERCENT dbo.AssetType.Description, dbo.AssetAttribute.AssetDescription, dbo.Asset.Barcode, dbo.Asset.SKU, dbo.ESNTracking.ReportTime, dbo.ESNTracking.CurrLocStreet, dbo.ESNTracking.CurrLocCity, dbo.ESNTracking.CurrLocState, dbo.ESNTracking.CurrLocZip, dbo.ESNTracking.CurrLocCounty, dbo.ESN.EsnNumber, dbo.ESNTracking.DistanceMiles, dbo.ESNTracking.MapUrl, dbo.InventoryOrigin.WarehouseDescription FROM dbo.AssetType INNER JOIN dbo.Asset ON dbo.AssetType.AssetTypeId = dbo.Asset.AssetTypeId INNER JOIN dbo.InventoryOrigin ON dbo.Asset.WarehouseId = dbo.InventoryOrigin.WarehouseId INNER JOIN dbo.AssetAttribute ON dbo.Asset.AssetAttributeId = dbo.AssetAttribute.AssetAttributeId INNER JOIN dbo.EsnAsset ON dbo.Asset.AssetId = dbo.EsnAsset.AssetId INNER JOIN dbo.ESN ON dbo.EsnAsset.EsnId = dbo.ESN.EsnId LEFT OUTER JOIN dbo.ESNTracking ON dbo.EsnAsset.EsnId = dbo.ESNTracking.EsnId LEFT OUTER JOIN dbo.AssetVehicle ON dbo.EsnAsset.AssetId = dbo.AssetVehicle.AssetId LEFT OUTER JOIN dbo.AssetCustomAttribute ON dbo.EsnAsset.AssetId = dbo.AssetCustomAttribute.AssetId LEFT OUTER JOIN dbo.AssetCustomAttributeDef ON dbo.AssetCustomAttribute.AssetTypeId = dbo.AssetCustomAttributeDef.AssetTypeId LEFT OUTER JOIN dbo.OrbitImport ON dbo.ESNTracking.EsnId = dbo.OrbitImport.OrbitImportId WHERE (dbo.ESNTracking.OrbitImportId = (SELECT MAX(OrbitImportId) AS Expr1 FROM dbo.ESNTracking AS ESNTracking_1)) ORDER BY dbo.AssetType.Description
I need to find the missing months in a table for the earliest and latest start dates per ID_No. As an example:
create table #InputTable (ID_No int ,OccurMonth datetime) insert into #InputTable (ID_No,OccurMonth) select 10, '2007-11-01' Union all select 10, '2007-12-01' Union all select 10, '2008-01-01' Union all select 20, '2009-01-01' Union all select 20, '2009-02-01' Union all select 20, '2009-04-01' Union all select 30, '2010-05-01' Union all select 30, '2010-08-01' Union all select 30, '2010-09-01' Union all select 40, '2008-03-01'
I have two table, tblCharge and tblSentence, for each charge, there are one or more sentences, if I join the two tables together using ChargeID such as: select * from tblCharge c join tblSentence s on c.ChargeID=s.ChargeID , all the sentences for each charge are returned. There is a field called DateCreated in tblSentence, I only want the latest sentence for each charge returned, how can I do this? I tried to create a function to get the latest sentence for a chargeID like the following: select * from tblCharge c join tblSentence s on s.SentenceID=LatestSentenceID(c.ChargeID) but it runs very slow, any idea to improve it? thanks,
I want to fetch below 3 records from the above scenario i.e. latest record of each amount (Latest is determined using "descr" column i.e. 4 is greater then 3 -
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.
Hi I have the same problem but those posts are no longer there. Are you able to help me out? I couldn't work it out so I created a date/time field called StartDate for when each record is entered. I was trying to use that to grab the particular eventID. Dim EventID = "" tbEventIDTest.Text = "" Dim EventDataSource1 As New SqlDataSource() EventDataSource1.ConnectionString = ConfigurationManager.ConnectionStrings("ASPNETDBConnectionString").ToString
EventDataSource1.SelectCommandType = SqlDataSourceCommandType.Text EventDataSource1.SelectCommand = "SELECT EventID FROM Event "WHERE ([StartDate] = @StartDate)" EventID = EventDataSource1.SelectParameters.Item(EventID) tbEventIDTest.Text = EventID Thanks, any help will be appreciated.
I am trying to create to a store procedure that manages to return the last 10 dates from a table i know there is a TOP keyword that return the first rows but is there a keyword that returns the last rows instead?
I have a database table which contains customer orders. I am trying to code my SQL select statement to:
1) Only return records where the record orderdate is within the last 30 days
2) Between two dates, selected from the datepicker control.
With regards to issue 1, I could fill a table with all the records for the account in question and then for each record do a datediff between the records order date and the current date to determine if the number of days is within 30 days. If yes then add this record to a temp table and then set this table as the datasource for the datagridview.
I am trying to write a query that takes the max recordID on table A, and increment it by 1 for every record that is inserted into table A. The recordID field does not identity field property turned on.
Can you give me some help in getting this done? Is what I am trying to do even possible?
I currently have a stored procedure that returns a list of dates based on a date range a user enters.
CREATE PROCEDURE sp_GetContactScheduleDates @MonthFrom int, @YearFrom int, @MonthTo int, @YearTo int, @DaysInMonth int AS Select distinct s.ScheduleMonth, s.ScheduleYear From OnCall_Schedules s Where CAST(cast(s.ScheduleMonth as nvarchar) + '/' + cast(s.ScheduleDate as nvarchar) + '/' + cast(s.ScheduleYear as nvarchar) as smalldatetime) >= CAST(cast(@MonthFrom as nvarchar) + '/' + cast('01' as nvarchar) + '/' + cast(@YearFrom as nvarchar) as smalldatetime) And CAST(cast(s.ScheduleMonth as nvarchar) + '/' + cast(s.ScheduleDate as nvarchar) + '/' + cast(s.ScheduleYear as nvarchar) as smalldatetime) <= CAST(cast(@MonthTo as nvarchar) + '/' + cast(@DaysInMonth as nvarchar) + '/' + cast(@YearTo as nvarchar) as smalldatetime) Order by s.ScheduleYear, s.ScheduleMonth GO
However, this only brings back those dates that are in the table. I need to get ALL dates within the range.
For example, the OnCall_Schedules table contains schedules that are saved by the user. If no one has ever saved a schedule at any time in May 2004 and the range of dates entered is January 2004 to June 2004, then May 2004 will not be returned. I need to get back all dates within that range regardless if it has something scheduled or not. How can this be done?
Note - I do not want to set up any dummy records or create a table with valid dates as the user will be allowed to choose any range of dates and we do not want to have to maintain anything.
Can some sort of function be used? What would the code look like?
Hi all,I have the following tableName Date Wish ValidName is person's name, date defaults to getdate() and is neverassigned directly (datetime field), Wish is some message, and Valid isbit, 1 indicates if the wish is the latest, and therefore valid. Allprevious wishes are kept in database, and are "invalidated" by settingthe Valid to 0.So, a typical data set looks like:Name Date Wish ValidJoe 02/01/2007 Ice Cream 0Joe 02/04/2007 Bicycle 0Joe 02/06/2007 PS3 0Joe 02/22/2007 XBox 360 1Mary 02/02/2007 Barbie 0Mary 02/04/2007 Cindy 0Mary 02/06/2007 Barbie house 0Mary 02/20/2007 Get married 1My users want to see the initial wish at some point and another onesome time later (they provide dates). So, if someone wanted to seechanges in wishes between 02/03 and till 02/15, they would get thatJoe's initial wish was Bicycle and the latest that he wanted was PS3.As for Mary, she started wanting Cindy and ended up thinking about theBarbie house.I can do UNION, but is there another way to do that?Thank you.
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
select DayRank = ROW_NUMBER() OVER(ORDER BY a.datedel DESC), a.order,a.line,a.datedel,a.recpt,b.status, b.item,b.t_sup from historytbl a inner join order b on a.order = b.order and a.line = b.line and a.status =4 group by a.order,line,a.datedel,a.recpt,b.status,b.item,b.sup
I have this specific problem, that has been causing me alot of headaches for the last couple of days, and I can't seem to fiure it out on my own.
Basically i am working on a many to one currency conversion setup, where I have a fact table with exchange rates for periods and for all input currencies. The reporting currency is USD. Here is a demonstration of the data in it:
Normal period by period conversion is easy enough, but I want to convert the measures at the latest known rate, based on the period selected. Lets say I run an analysis without slicing on time, then it want it to convert at the last entered rate of all time, and if the user wants to run the analysis as of March 08, then it should convert all data to the rate as of January, since this is the latest one known.
I have tried to set the measure to a semi-additive behaviour, with "lastnonempty", but the problem with that is the conversion over time. Here is an example:
I want to show a measure summed "all to date" as of June 08. What I want is it to convert everything at the rates entered in April 08, but what I get is that it convert everything up until Jan 08 and the rates entered in January, and thereafter it starts to use the rated entered in April.
Period Amount LCY Currency Code Exchange Rate Dec 07 100 GBP 2.0563 (Wrong, should be 1.9968) Dec 07 100 EUR 1.4634 (Wrong, should be 1.5197) Jan 08 100 GBP 2.0563 (Wrong, should be 1.9968) Jan 08 100 EUR 1.4634 (Wrong, should be 1.5197) Feb 08 100 GBP 1.9968 Feb 08 100 EUR 1.5197 Mar 08 100 GBP 1.9968 Mar 08 100 EUR 1.5197 Apr 08 100 GBP 1.9968 Apr 08 100 EUR 1.5197 May 08 100 GBP 1.9968 May 08 100 EUR 1.5197 Jun 08 100 GBP 1.9968 Jun 08 100 EUR 1.5197
How do I create a measure containing the latest known rates based on time selection?
I have a table T (a1, ..., an, time, id). I need to select those rows that have different id (GROUP BY id), and from each "id group" the row that has the latest field 'time'. Something like SELECT a1, ..., an, time, id ORDER BY time DESC GROUP BY id. This is the wrong syntax and I don't know how to handle this.
hopefully someone can suggest the best way of implementing the problem i am trying to resolve. We have a table which contains rows relating to tests run on our product. This table is populated from an SSIS job which parses CSV files.
There are multiple rows per serial number relating to multiple tests. The only tests i am interested in are the ones with an ID of T120. Here is the query i have so far which should make it a little easier to explain:
SELECT [SerialNumber] ,Param1 ,[TimeStamp] FROM [Build Efficiency System].[dbo].[SSIS_SCANNERDATA_TBL] WHERE Test = 'T120' GROUP BY SerialNumber, Param1, [TimeStamp] ORDER BY SerialNumber
What i have above is fine to a point. The problem i am encountering is that in test T120 it specifies a part which can be be one of about 6 in field Param1. If during testing there is a problem with the part then it is replaced and the test run a second time up until the whole product passes the test. The query above returns all instances of replacements so i may have the out put as follows:
I have the following table called BADSANTA: varchar(30) datetime NAME WHENBAD OJ Simpson 2007-1-12 xx:xx:xx:xxx OJ Simpson 2007-4-2 xx:xx:xx:xxx Monica Lewinsky 2006-7-4 xx:xx:xx:xxx Monica Lewinsky 2006-10-31 xx:xx:xx:xxx Bill Clinton 2006-7-4 xx:xx:xx:xxx Bill Clinton 2006-10-31 xx:xx:xx:xxx Bart Simpson 2006-11-2 xx:xx:xx:xxx Bart Simpson 2006-2-25 xx:xx:xx:xxx Bart Simpson 2005-07-27 xx:xx:xx:xxx
I want the records of the persons latest WHENBAD date. It should return one recordset for each person.
i need a query to return the top 10 tables in each database on a server. have used EXEC sp_msforeachtable 'sp_spaceused ''?''' which returns what I need for one db but I need it to loop through and gather the info for all dbs on server. maybe need cursor not sure. for reporting reasons i would like to include the name of the server and name of database.
Hello can some one explain this to me and give me some advice. I have sqlserver1 and sqlserver2 I have a linked server set up [ipaddress] on both servers. When I pass a variable to the stored proc or the query it takes up to 20 seconds to return 1 row but if I replace my varibles like email='sqlboy@coxnet' and firstname='ted' and lastname='clien' it returns the one row im looking for in about 2 seconds but if I pass email =@email ,fname=@fname,lname=@lname I get the 20 second thing. The query is a stored proc being called from an asp app. I get the same results when I run this in query analyzer.
IF EXISTS (SELECT TOP 1 email FROM [ipaddress].{database}.dbo.{tablename}--server1 WHERE email = @email ) BEGIN set nocount on SELECT TOP 1 email, FIRSTNAME, MIDDLENAME, LASTNAME, TITLE, COMPANYNAME, ADDRESS1, ADDRESS2, CITY, STATE, ZIP, COUNTRY FROM [ipaddress].{database}.dbo.{tablename} --server2 WHERE email in(SELECT EMAIL FROM [ipaddress].{database}.dbo.{tablename} where email=@email--server1) AND RecordStatusID ='1' and FirstName=@fname and LastName=@lname END ELSE
IF EXISTS (SELECT top 1 email, FIRSTNAME, MIDDLEINITIAL, LASTNAME, TITLE, COMPANYNAME, ADDRESS1, ADDRESS2, CITY, STATE, ZIP, COUNTRY FROM {databases}.dbo.attendees--server1 WHERE email =@email and FirstName=@fname and LastName=@lname) BEGIN SELECT TOP 1 email, firstname, MIDDLEINITIAL AS MIDDLENAME, lastname, title, companyname, address1, address2, city, state, zip, country FROM {database}.dbo.attendees --server1 WHERE email in (SELECT DISTINCT email FROM server1.dbo.ebooksrequests--server1 where email=@email) and email=@email and FirstName=@fname and LastName=@lname SET NOCOUNT OFF
I have two tables I am working with, they are "Institutions" and "InstitutionOversights". The relationship is one-to-many.
The sample data is below.
Table one: InstitutionID, InstName ------------------------ 1 School Alpha 2 School Beta 3 School Charlie 4 School Delta
Table two: InstitutionOversightID, InstitutionID, Type ------------------------------------------------ 1 1 Accreditation 2 1 Verifcation 3 1 Old System
I would like a query to return the results in the following format:
InstitutionID, InstName, TypeList ----------------------------------------------- 1 School Alpha Accreditation, Verification, Old System 2 School Beta null 3 School Charlie null 4 School Delta null
OLE DB provider "SQLNCLI11" for linked server returned message "Query timeout expired". [SQLSTATE 01000]
A linked Server was set up against a remote database to backup a database and it runs perfectly well when executed directly against the remote server but returns the above error when set up through Sql Server Agent. Permissions are good as the step returns success. I reset the query timeout property to zero but error persist. What else should I be looking at to make this work?
How to design at database level such a way so that when I implement a SQL query that returns one hundred thousand rows only display 25 rows at the client (Web page at a time). How can I accomplish this?
Once I display first 25 rows then how do I bring next 25 rows and so on. Can it be done via paging or there are other techniques. However I asked to design this in the database level. I am using MS SQL Server 2008. Front end Visual Studio 2010. I use C# for coding.
My requirements are to return the sales for each customer for each store, for the past 6 weeks.
The catch is that I only want those customers which have had sales over 10,000 within the last week.
This is my query:
WITH SET [CustomerList] AS FILTER( ([Store].[Store Name].[Store Name], [Customer].[Customer Name].[Customer Name]), [Measures].[Sales] >= 10000 AND [Date].[Fiscal Week Name].&[2015-01-26 to 2015-02-01]
I have written this sample query to search a full-text indexed table and return the results. If the word occurs more than once I want it to return as a new record and the results show a short summary of the location. I was using 'like', but the full table scans were really slowing it down. Can performance be improved for the following (The results returned by my query are accurate)