I have a table (SQL Server 2000) with several date columns in it, all of
which are individually NULLable, but in any one row, not all the dates can
be NULL.
I want a query which ORDERs BY the earliest date it finds in each row. I'm
guessing I have to do this in two steps:
STEP 1
Using a UDF, find the earliest date and stick it in a new calculated
column "earliest date"
STEP 2
ORDER BY this UDF-created column
If this is the right way to go about this, is there a simple SQL way of
determining which is the lowest of several dates? (ie of doing STEP 1).
Or am I looking at this the wrong way, and missing an easy *one-step* way of
getting what I want?
I'm having a mental block on a select statement.I have a table with the following columns:KitId int LotNo varchar(10) DateReceived smalldatetimeIt is possible to have many rows with the same LotNo but a differing DateReceived I need to write a select statement that returns the KitId for a given LotNo with the earliest DateReceivedso if I had rows:KitId =1, LotNo = 123, DateReceived = 11th May 2008KitId =2, LotNo = 123, DateReceived = 28th May 2008KitId =3, LotNo = 125, DateReceived = 28th May 2008KitId =4, LotNo = 127, DateReceived = 28th May 2008KitId =5, LotNo = 123, DateReceived = 12th June 2008I would want to retrieve KitId=1 if I provided LotNo 123 as a parameter Whilst it should always be the case that the LotNo with the earliest date will have the lowest KitId I cannot guarantee that will be the case so going for the lowest KitId isn't an optionCan one of you SQL gurus provide me with the statement I need?ThanksNeil
I have this query which I pasted below. I need to find the earlist effective date (pcsp_eff), but I need to show all of the fields below in my report like a flat file. I know ususaly when you use Max/Min you have to have a group by, would I group by everything that is in my select statement?
SELECT Distinct dbo.pcs.pcs_id1, dbo.pcs.pcs_lname AS [Last Name], dbo.pcs.pcs_fname AS [First Name], dbo.pcsp.pcsp_eff AS [Effective Date for Provider], Min(pcsp_eff) as "earliestEffectivedate", dbo.pcst.pcst_trm1 AS [Tracking Thru Date], dbo.pcst.pcst_dat3 AS [Re-cred Letter Sent Date], dbo.pcst.pcst_dat7 AS [Re-cred Complete Date], PRO_STATE as "State", PRO_COUNTY as "County"--, PCSP_NET
FROM dbo.pcs INNER JOIN dbo.pcst ON dbo.pcs.pcs_id1 = dbo.pcst.pcst_id1 INNER JOIN pcsp ON pcs.pcs_id1 = pcsp.pcsp_id1 left Join dbo.pro ON pcs.pcs_id1 = pro.pro_id1
WHERE (CONVERT(CHAR(10), dbo.pcst.pcst_dat3, 110) <>'03-23-1977') and (CONVERT(CHAR(10), dbo.pcst.pcst_dat7, 110) = '03-23-1977') and (pcsp.pcsp_prd = 'DGH') AND --(pcsp.pcsp_id2 = '0001') and PCS_CTL = 'I' and pcsp_NET <> 'DACFP' and pcs_id1 = '00004307'
I want to find out the earliest [First_Post_Date] for any parentdid
My query (See below) Produces the following results SELECT ParentID ,[First_Post_Date] ,[FDMSAccountNo] FROM [FDMS].[dbo].[Dim_Outlet] where ParentID = '878595212886' Order by ParentID desc
hi basically what i have is 3 text boxes. one for start date, one for end date and one for order id, i also have this bit of SQL SelectCommand="SELECT [Order_ID], [Customer_Id], [Date_ordered], [status] FROM [tbl_order]WHERE (([Date_ordered] >= @Date_ordered OR @Date_ordered IS NULL) AND ([Date_ordered] <= @Date_ordered2 OR @Date_ordered2 IS NULL OR (Order_ID=ISNULL(@OrderID_ID,Order_ID) OR @Order_ID IS NULL))"> but the problem is it does not seem to work! i am not an SQL guru but i cant figure it out, someone help me please! Thanks Jez
because the bankruptcy_date date are all equal i would need to pull one record with the earliest date from the doc_received_date. The date with the arrow is the record i want. So basically i would like to show this result
Hello all,Quick sql syntax question:I have this table:if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[REQUESTS]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)drop table [dbo].[REQUESTS]GOCREATE TABLE [dbo].[REQUESTS] ([ROW_ID] [uniqueidentifier] NULL ,[REQUEST_DATE] [datetime] NULL ,[STATUS] [tinyint] NULL) ON [PRIMARY]GOwith these values:insert into REQUESTS (REQUEST_DATE, STATUS)values (getdate(), 0)insert into REQUESTS (REQUEST_DATE, STATUS)values (getdate(), 1)insert into REQUESTS (REQUEST_DATE, STATUS)values (getdate(), 0)I need to select the single record with a STATUS = 0 with the earliestREQUEST_DATEI am using this query:SELECT TOP 1 ROW_ID FROM REQUEST_LOG WHERE STATUS = 0 ORDER BYREQUEST_DATEnot sure if this is the way to go...pointer appreciatedthanks
I'm no SQL whizz yet but I'm learning hard, and need to get some information from our DB rather urgently so have resorted to this fantastic forum, only I can't find what I'm looking for.
Basically I'm selecting a whole load of entries that have a (admission)date field after 2001, but I only want to return the Earliest (admission) for each (patients number).
Here is the script I have created to select all the data, but how can I limit the results to just the earliest (admission date) for each (patient).
SELECT Admission_Year, Admission_Month, Age_On_Admission, [Length of stay(continuing)], [Patient's Number], [Cons epis seq no], Sex, [Main Primary Pas Diag], [Date of Death], [Epi duration], [OP Code1], [Admission date], [Date of Death] - [Admission date] AS [days before death],[Intended Management] FROM dbo.Admissions WHERE (Admission_Year > 2001) AND (Age_On_Admission > '64') AND ([Intended Management] = 'inpatient') AND ([Date of Death] IS NULL)
I would really appreciate it if anyone can help with this, I'm sorry I can't really contribute to this forum as an SQL expert as .net is really my forte and I usually spend my time contributing to the asp.net forums. :)
Hi!I have a little problem. I’m trying to sort a date I have converted like thisConvert(datetime,LH.LoginDateTime,103) as RegistrationDateBut when I use Order by on RegistrationDate it only sort on days:01/11/200601/12/200602/11/200602/12/200603/11/200603/12/2006I’ll guess it’s because of the “varchar� convert, but I need the date to bee inn this format, since I only shall check the date and not the time. Is there a way around this, so I can order it like this? (Se under)01/11/200602/11/200603/11/200601/12/200602/12/200603/12/2006Sample SQL;select Convert(varchar,LH.LoginDateTime,103) as RegistrationDate,select count(*) from LoginHistory AS LH2 where datepart(hh,LH2.LoginDateTime)<7 ANDConvert(varchar,LH2.LoginDateTime,103)>=Convert(varchar,LH.LoginDateTime,103) AND Convert(varchar,LH2.LoginDateTime,103)<=Convert(varchar,LH.LoginDateTime,103)) As beforehour07from LoginHistory AS LHwhere LH.LoginDateTime >='''+ Convert(varchar,@FromDate,113) + ''' ' + 'and LH.LoginDateTime <='''+ Convert(varchar,@ToDate,113) + ''' ' + 'group by Convert(varchar,LH.LoginDateTime,103)'Order by RegistrationDate
Hello there,I have a problem when I'm trying to order by the date..I have tried this string:SelectCommand="SELECT TOP 5 [Date], [Id], [Navn], [ShortInfo] FROM [fest] ORDER BY [Date] DESC"> And I have these dates:
04/02/2008
06/02/2008
20/02/2008
29/02/2008
08/03/2008
28/03/2008They should be shown like this:
04/02/2008
06/02/2008
20/02/2008
29/02/2008
08/03/2008 But they dosn't, insted is they shown like this:
29/02/200828/03/200820/02/200808/03/200806/02/2008How can I do, so it work?Regards Jeppe Richardt
Here is my sp. I want it to order by descending date, but now it is 1st Feb it is putting this at the bottom, though January is still sorted fine. I need the dates to display in UK format dd/mm/yy
CREATE Procedure [dbo].[spRMU_CountNoDailyUsers]
AS SELECT CONVERT(varchar, Log_DateTime, 103) AS Date_Logged_In, Log_Username as Username, COUNT(Log_Username) AS No_Logins FROM tblUserLog Where Log_Printed =0 GROUP BY CONVERT(varchar, Log_DateTime, 103) , Log_Username ORDER BY CONVERT(varchar, Log_DateTime, 103) desc, No_Logins desc GO
SELECT LEFT(CONVERT(CHAR(11),convert(datetime,task_date),109),3) + ' ' + RIGHT(CONVERT(CHAR(11),convert(datetime,task_date),109),4) as Date, SUM(CASE a.status_id WHEN 1000 THEN b.act_point ELSE 0 END) as Programming, SUM(CASE a.status_id WHEN 1016 THEN b.act_point ELSE 0 END) as Design, SUM(CASE a.status_id WHEN 1752 THEN b.act_point ELSE 0 END) as Upload, SUM(CASE a.status_id WHEN 1032 THEN b.act_point ELSE 0 END) as Testing, SUM(CASE a.status_id WHEN 1128 THEN b.act_point ELSE 0 END) as Meeting, SUM(CASE a.status_id WHEN 1172 THEN b.act_point ELSE 0 END) as Others From task_table a,act_table b where a.status_id=b.act_id and a.user_id=(select user_id from user_table where user_name='Raghu') and a.task_date like '%/%/2006' GROUP BY LEFT(CONVERT(CHAR(11),convert(datetime,task_date),109),3) + ' ' + RIGHT(CONVERT(CHAR(11),convert(datetime,task_date),109),4)
It is all contained in one table. I have got the earliest years by using the YEAR() function and grouping by it. The only problem is that I am having a problem joining the table back onto itself with the subselect because of it's an aggregate.
Here is the first join I have....
SELECT DT.ClientID, Year1 FROM ( SELECT ClientID, YEAR(MyDate) as Year1 FROM MyTable ) AS DT GROUP BY ClientID, Year1 ORDER BY ClientID, Year1
I want to use that as my derived table and then join back to it... but it's not working...
Finding the earliest datetime entry, and then updating the database on these reults.
I need to query a table of data that has multiple datetime entries in it relating to individual customer records. So one customer could have 1 entry, or it could have 10 entries. I need to be able to identify the earliest of these records, and then on this earliest record update a field value. Example:
My Fields in the table are as follows. Log_ID, Cust_Ref_No, ActionDateTime, Action_Code
The Log_ID is the primary key, and I need to update the Action_Code field on only the earliest entry against a customer record i.e.
hi,I was pulling up a report in SQL, and I wanted the records to be ordered by dates descending. However, I found this ordering was only fine enough to order records by dates (not hours or minutes) (within the same date, records were ordered so that the latest entered were at the bottom). I wonder if anyone else has encouted this problem before, or I am doing something wrong.Thanks very much.
I have a problem with an Order By sort on a SubmissionDate column in my SQLSERVER DB.
I am inputing a timestamp in this format into the column above: 1/18/2005 11:03:19 AM
Problem is, once I sort this column in DESC order to return the results to a datalist dates with a time like this:
1/18/2005 1:03:19 AM
get placed out of place (lower on the return in DESC/higher on the return in ASC). I am assuming this is happening because it reads 1 as coming before 11 instead of after like it is with time. If this was in 24 hour format this wouldn't be a problem I guess because 1PM would be 13, so that is after 11.
Anyone know what I can do to get this sorted correctly?
hi. i'm trying to order my results ascending by date except i'm getting some really weird output. my ouput resembles something like this:
oct 2 oct 3 sep 13 sep 21 sep 22 sep 30 aug 3 aug 5 aug 16
the data is stored in a date field. i use getdate when inserting the date to the database. is there a reason why the dates are showing up weird and not ordering appropriately? thanks for your help.
also, can you not search here any more? i keep getting timeout errors.
Payment Order_Number|Card_Type|Card_#|Merchant 10001 Gift Card1234null 10001 Gift Card1235null 10001 Gift Card 1236null 10001 Credit Cardxxxxprd 10002 Credit Cardxxxxprd 10003 Credit Card xxxxprd 10004 Credit Card xxxx prod
I have to populate th below table to track last gift card used for each cust_number. 1. last gift card used for each customer, each order 2. In a single order , if card used is gift card, last gift card used is gift card itself. if card used is a credit card, then the max gift card number from with in the order. 3. First time if a customer uses a credit card, then last gift card used is defaulted to 99 for merchant = prd and 88 for merchant = prod 4. In a new order, a past customer only uses a gift card, then last gift card used is gift card from his previous order.
Please help me with the sql. I tried this using subqueries to find the max gift card for a customer for an order and could get the last gift card used correctly for credit cards for an order, but not able to insert the gift card from a previous order if the new order has only credit card as in for customer C1.
I have below SQL, which should be order by posteddate ASC
SELECT AnnouncementID,[Subject],[Description], CONVERT(nvarchar(10),PostedDate,101) AS PostedDate, CONVERT(nvarchar(10),ExpiredDate,101) AS ExpiredDate, CountryID,CreatedBy, CreatedDate, ModifiedBy, ModifiedDate FROM Announcements a WHERE isActive = 1 AND CountryID = 2 AND (GETDATE()>= PostedDate) AND (GETDATE()<= ExpiredDate) ORDER BY PostedDate ASC
But result is displaying as below, PostedDate datatype is datetime
How do I order a query by a date field ASC, but have any NULL valuesshow up last? i.e.7/1/20037/5/20037/10/2003<NULL><NULL>Any help will greatly be appreciated
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NWHCConnectionString %>" SelectCommand="SELECT [Title], [URL], [Date] FROM [Article] ORDER BY [Date] DESC"></asp:SqlDataSource>
<asp:Repeater id="myRepeaterUL" runat="server" DataSourceID="SqlDataSource1"> <HeaderTemplate> <ul> </HeaderTemplate> <ItemTemplate> <li><a href="<%# DataBinder.Eval(Container.DataItem, "URL") %>"><%#DataBinder.Eval(Container.DataItem, "Title")%></a><br /><%# Eval("Date") %></li> </ItemTemplate> <FooterTemplate> </ul> </FooterTemplate> </asp:Repeater> This is my code above, I am trying to order them to show the four new list of news. Here is a picture, yeah its old and everybody loves pictures. see the box on the right, i want to show only four, not all of it.
When clicking on the header for the Date Created column in EM (SQL Server 2000) , in the tables list for a database, I noticed that the tables don't get sorted by created date at all - looks like random order, without looking too close.
Is this is a bug (probably not??) or some kind of collation-related problem?
Below SQL gives the results of 2 columns and I need the DepartmentandDate column to be ORDER BY on date desc for that CID. Expected result is in the screenshot(attachment)...
IF OBJECT_ID('Tempdb..#tTable') IS NOT NULL DROP TABLE #tTable CREATE TABLE #tTable(CID INT, CDate DATETIME, Dept VARCHAR(25)) INSERT INTO #tTable(CID, CDate, Dept) VALUES (111, '2014-01-14 00:00:00.000','B is alphabet'),
how do you get it to sort correctly for the date? at the minute its sorting on the characters rather than actual date value
Code Snippet INSERT INTO @TempItems (OrderID) SELECT OrderID FROM Orders o INNER JOIN Customers c ON c.CustomerID = o.CustomerID INNER JOIN Employees e ON e.EmployeeID = o.EmployeeID ORDER BY CASE @SortOrder --Order ASC WHEN 0 THEN cast(OrderID as varchar(100)) WHEN 1 THEN cast(c.CompanyName as varchar(100)) WHEN 2 THEN cast(e.FirstName as varchar(100)) WHEN 3 THEN cast(o.OrderDate as varchar(100)) WHEN 4 THEN cast(o.RequiredDate as varchar(100)) WHEN 5 THEN cast(o.ShippedDate as varchar(100)) ELSE '1' END,
I have a report that displays its date dropdown badly: 10AM,10PM, 11AM, 11PM etc when it should be 10AM, 11AM, etc. The used measure is Hour Name which looks like "01AM" "02AM" etc. And here is the current query
WITHÂ MEMBER [Measures].[ParameterCaption] AS [Report Verified Time].[Hour Name].CURRENTMEMBER.MEMBER_CAPTIONÂ MEMBER [Measures].[ParameterValue] AS [Report Verified Time].[Hour Name].CURRENTMEMBER.UNIQUENAME MEMBER [Measures].[ParameterLevel] AS [Report Verified Time].[Hour Name].CURRENTMEMBER.LEVEL.ORDINALÂ SELECT {[Measures].[ParameterCaption], [Measures].[ParameterValue],Â
I am working on a query that needs to return the record order number with the most recent requested delivery date.
It seems to work most of the time, but I have found some glitches for some of the items.
example is my item 10702, it is showing 2 records (both valid ones) Record 1 is order # 10450-0, requested delivery date 03/21/2014 Record 2 is order # 10510-0, requested delivery date 04/29/2014
I need to only get the records with the most recent delivery date, in this example that would be 04/29/2014
This query is what I have so far:
SELECT s.PriorQuoteNumber ,s.PriorItemNumber ,s.PriorQuoteDate FROM ( SELECT s.SalesQuoteNumberAS 'PriorQuoteNumber'
[code]....
WHERE s.rn = 1What am I missing in my query> how can I change it so it only returns the most recent date?
I am using Access 2003 as a front-end to a SQL Server 2005 database.I make design changes using SQL Server Management Studio. I have atable that includes a datetime column. I create a view and sort bythe datetime field. When I initially look at the result it is sortedcorrectly. Then I save the view and re-open it and it is not sorted.I've simplified the view so it only contains the date field and itstill does not sort. Here is the view:SELECT TOP (100) PERCENT Period_DateFROM dbo.Period_SummaryORDER BY Period_Date DESCThe date seems to be a random order.I don't have this problem in the SQL Server 2000 version of thedatabase.Help please!Thanks,Jerry
I'm having problems with a stored procedure, that i'm hoping someone can help me with.
I have a table with 2 columns - Username (varchar), LastAllocation (datetime)
The Username column will always have values, LastAllocation may have NULL values. Example
Username | LastAllocation ------------------------ Greg | 02 October 2005 15:30 John | 02 October 2005 18:00 Mike | <NULL>
My stored procedure needs to pull back a user name with the following criteria:
If any <NULL> dates send username of first person where date is null, sorted alphabetically, otherwise send username of person with earliest date from LastAllocation
Then update the LastAllocation column with GETDate() for that username.
This SP will be called repeatedly, so all users will eventually have a date, then will be cycled through from earliest date. I wrote an SP to do this, but it seems to be killing my server - the sp works, but I then can't view the values in the table in Enterprise Manager. SP is below - can anyone see what could be causing the problem, or have a better soln? Thanks Greg ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ CREATE PROCEDURE STP_GetNextSalesPerson AS DECLARE @NextSalesPerson varchar(100)
BEGIN TRAN
IF (SELECT COUNT(*) FROM REF_SalesTeam WHERE LeadLastAllocated IS NULL) > 0 BEGIN SELECT TOP 1 @NextSalesPerson = eUserName FROM REF_SalesTeam WHERE LeadLastAllocated IS NULL ORDER BY eUserName ASC END ELSE BEGIN SELECT TOP 1 @NextSalesPerson = eUserName FROM REF_SalesTeam ORDER BY LeadLastAllocated ASC END
SELECT @NextSalesPerson UPDATE REF_SalesTeam SET LeadLastAllocated = GETDATE() WHERE eUserName = @NextSalesPerson