I have a date column CreateDate (datetime, not null) in my table.
Using the following where clause:
Where
-- Code for 12 Months Back at a Time
CreateDate >= dateadd(month,datediff(month, 0, getdate())-12,0)
If I run my report say on March 1, 2017, I should get 12 months of data. I do.
I would like to order by CreateDate and get the following order
Mar 2017
Feb 2017
Jan 2017
Dec 2016
Nov 2016
Oct 2016
Sep 2016
Aug 2016
Jul 2016
Jun 2016
May 2016
Apr 2016
Here is the complete query:
SELECT DISTINCT
tblCourtAttorneysAssigned.CourtAssignment AS [CourtAssignment],
tblCourtAttorneysAssigned.AttorneyBarNumber AS [AttorneyBarNumber],
tblCourtAttorneysAssigned.AttorneyFirstName AS [AttorneyFirstName],
tblCourtAttorneysAssigned.AttorneyLastName AS [AttorneyLastName],
--tblCourtAttorneysAssigned.CaseNo,
--tblPeople.LastName,
--tblPeople.FirstName,
tblCourtAttorneysAssigned.HowAssigned AS [HowAssigned],
CONVERT( VARCHAR(10), tblCourtAttorneysAssigned.CreateDate, 101) AS[CreateDate]
FROM tblBookIn
INNER JOIN tblOffense ON tblBookIn.BookInID = tblOffense.BookInID
INNER JOIN tblPeople ON tblBookIn.PersonID = tblPeople.PersonID
INNER JOIN tblCourtAttorneysAssigned ON tblOffense.CaseNo = tblCourtAttorneysAssigned.CaseNo
WHERE CourtAssignment LIKE 'M%'
AND
-- Code for 12 Months Back at a Time
CreateDate >= dateadd(month,datediff(month, 0, getdate())-12,0)
ORDER by
[CreateDate] asc
--courtassignment ASC,
-- AttorneyLastName ASC;
Thanks
I am guessing you are using order by CreateDate desc but you have aliased CreateDate in your query to be something like format(CreateDate, 'MMM yyyy') as CreateDate
So your order by will need to know you want it to use the original value instead of the new value that is being returned with the same name.
Try order by mytablename.CreateDate desc
Update after question edited to include query:
change your order by to:
order by tblCourtAttorneysAssigned.CreateDate desc
I think you should use order by clause at the end
SELECT { fn MONTHNAME(OrderDate) } AS MonthName, YEAR(OrderDate) AS Year, SUM(TotalValue) AS Profits
FROM [Order]
WHERE (YEAR(OrderDate) = #year)
GROUP BY { fn MONTHNAME(OrderDate) }, YEAR(OrderDate)
ORDER BY { fn MONTH(OrderDate) }, YEAR(OrderDate)
or
you can do like this
SELECT CASE { fn MONTH(OrderDate) }
when 0 then 'JAN'
when 1 then 'FEB'
when 2 then 'MAR'
when 3 then 'APR'
when 4 then 'MAY'
when 5 then 'JUN'
when 6 then 'JUL'
when 7 then 'AUG'
when 8 then 'SEP'
when 9 then 'OCT'
when 10 then 'NOV'
when 11 then 'DEC'
END
AS MonthName, YEAR(OrderDate) AS Year, SUM(TotalValue) AS Profits
FROM [Order]
WHERE (YEAR(OrderDate) = #year)
GROUP BY { fn MONTH(OrderDate) }, YEAR(OrderDate)
ORDER BY { fn MONTH(OrderDate) }, YEAR(OrderDate)
Thanks all, I have resolved the issue by removing the Convert on the date field and fixing the format in SSRS.
Thanks,
Related
My tables combined look something like:
Seller_ID |From |To |Depart_Date |Arrival_Date
-------------------------------------------------------------------------------------
Paul |office |client_23 |10/20/2015 3:30:00 PM |10/21/2015 7:54:00 AM
Paul |client_23 |client_ 88fe |10/21/2015 11:55:00 AM |10/22/2015 8:11:00 PM
Paul |client_88fe |client_avr4 |10/23/2015 3:57:00 PM |10/26/2015 11:27:00 AM
Paul |client_avr4 |home |10/26/2015 5:28:00 PM |10/28/2015 3:39:00 PM
I do not have a indicator like first visit, second visit, third visit...
First visit always has 'From' = office and last visit always has 'To' = home.
Only way to make the sequence is either go backwards by Dates (or by From-To ??)
My desired outcome would be :
|Seller_ID |from |office_departure |client1 |clt1_arrival |clt1_departure |client2 |clt2_arrival |clt2_departure |client3 |clt3_arrival |clt3_departure |home_arrival
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|Paul |office |10/20/2015 3:30:00PM |client_23 |10/21/2015 7:54:00 AM|10/21/2015 11:55:00 AM |client_ 88fe|10/22/2015 8:11:00 PM |10/23/2015 3:57:00 PM |client_avr4 |10/26/2015 11:27:00 AM |10/26/2015 5:28:00 PM |10/26/2015 5:28:00 PM
Any help is apreciated!
thanks in advance.
If your case is just one trip per seller, or that you have another field not shown here that you can use in group by, you can use something like this:
select
Seller_ID,
max(case when RN = 1 then [From] end),
max(case when RN = 1 then [Depart_Date] end),
max(case when RN = 1 then [Arrival_Date] end),
max(case when RN = 2 then [From] end),
max(case when RN = 2 then [Depart_Date] end),
max(case when RN = 2 then [Arrival_Date] end)
from (
select
row_number() over (partition by Seller_ID
order by Depart_Date asc) as RN,
*
from Table1
) X
group by Seller_ID
Result:
Seller_ID
Paul office October, 20 2015 15:30:00 October, 21 2015 07:54:00 client_23 October, 21 2015 11:55:00 October, 22 2015 20:11:00
Example in SQL Fiddle
If you don't have any field for tracking the number of trip, you can use running total in order of departure date for statement case when [From] = 'office' then 1 else 0 end partitioned by Seller_ID, that will then assign trip number for the rows.
I am running SQL Server 2014 and I have the following T-SQL query:
USE MYDATABASE
SELECT *
FROM RESERVATIONLIST
WHERE [MTH] IN ('JANUARY 2015','FEBRUARY 2015')
RESERVATIONLIST mentioned in the code above is a view. The query gives me the following output (extract):
ID NAME DOA DOD Nights Spent MTH
--------------------------------------------------------------------
251 AH 2015-01-12 2015-01-15 3 JANUARY 2015
258 JV 2015-01-28 2015-02-03 4 JANUARY 2015
258 JV 2015-01-28 2015-02-03 2 FEBRUARY 2015
The above output consist of around 12,000 records.
I need to modify my query so that it eliminates all duplicate ID and give me the following results:
ID NAME DOA DOD Nights Spent MTH
--------------------------------------------------------------------
251 AH 2015-01-12 2015-01-15 3 JANUARY 2015
258 JV 2015-01-28 2015-02-03 4 JANUARY 2015
I tried something like this, but it's not working:
USE MYDATABASE
SELECT *
FROM RESERVATIONLIST
WHERE [MTH] IN ('JANUARY 2015', 'FEBRUARY 2015')
GROUP BY [ID]
HAVING COUNT ([MTH]) > 1
Following query will return one row per ID :
SELECT * FROM
(
SELECT *,ROW_NUMBER() OVER (PARTITION BY ID ORDER BY (SELECT NULL)) rn FROM RESERVATIONLIST
WHERE [MTH] IN ('JANUARY 2015','FEBRUARY 2015')
) T
WHERE rn = 1
Note : this will return a random row from multiple rows having same ID. IF you want to select some specific row then you have to define it in order by. For e.g. :
SELECT * FROM
(
SELECT *,ROW_NUMBER() OVER (PARTITION BY ID ORDER BY DOA DESC) rn FROM RESERVATIONLIST
WHERE [MTH] IN ('JANUARY 2015','FEBRUARY 2015')
) T
WHERE rn = 1
definitely, it will return the row having max(DOA).
You are trying to do a GROUP BY statement which IMHO is the right way to go. You should formulate all columns that are a constant, and roll-up the others. Depending on the value of DOD and DOA I can see two solutions:
SELECT ID,NAME,DOA,DOD,SUM([Nights Spent]) as Nights,
min(MTH) as firstRes, max(MTH) as lastRes
FROM RESERVATIONLIST
GROUP BY ID,NAME,DOA,DOD
OR
SELECT ID,NAME,min(DOA) as firstDOA,max(DOD) as lastDOD,SUM([Nights Spent]) as Nights,
min(MTH) as firstRes, max(MTH) as lastRes
FROM RESERVATIONLIST
GROUP BY ID,NAME
What I want: I would like a result set that shows me the 10 years prior to and the 10 years after the current year.
Example: Being that this year is 2014:
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
What I've tried: I'm not a huge SQL guy so bear with me here:
SELECT
YEAR(DATEADD(year, -10, GETDATE())) AS prevYear,
YEAR(DATEADD(year, 10, GETDATE())) AS nextYear,
YEAR(GETDATE()) AS currentYear
WHERE currentYear BETWEEN prevYear AND nextYear
Can someone help me out? Am I even close??
SELECT TOP (21) YEAR(DATEADD(YEAR, number-10, GETDATE()))
FROM master.dbo.spt_values WHERE type = N'P' ORDER BY number;
Chances are you want to do something else with this data. One example might be to aggregate the data from some table, and include years in this range that aren't found in the table. Here's how you might do that:
;WITH y(d) AS
(
SELECT TOP (21) DATEADD(YEAR, number-10, DATEADD(YEAR, YEAR(GETDATE())-1900,0))
FROM master.dbo.spt_values WHERE type = N'P' ORDER BY number
)
SELECT y.d, COUNT(o.key)
FROM y
LEFT OUTER JOIN dbo.other_table AS o
ON o.datetime_column >= d.d
AND o.datetime_column < DATEADD(YEAR, 1, d.d)
GROUP BY y.d
ORDER BY y.d;
Assuming you need to get these records from an existing table:
declare #thisYear int = year(getdate())
select yourYear
from table1
where yourYear between #thisYear -10 and #thisYear + 10
and yourYear <> #thisYear --Assuming you don't need the current year
SQL fiddle demo
How can I extract the year and week combination from a date in SQL Server using T-SQL and have it match the MySQL yearweek result?
For example these MySQL queries (Click here for MySQL SQL Fiddle):
SELECT yearweek('2013-12-31');
SELECT yearweek('2014-01-01');
This returns 201352 for both dates. That is the expected result.
But in SQL Server...
datepart works as expected for the year extract
sometimes datepart does not return the expected value for iso_week
The MySQL result cannot be achieved with this T-SQL query...
SELECT datepart(year, #dt) * 100 + datepart (iso_week, #dt);
T-SQL versions of the MySQL queries above (Click here for T-SQL SQL Fiddle):
SELECT datepart(year, '2013-12-31') * 100 + datepart (iso_week, '2013-12-31');
SELECT datepart(year, '2014-01-01') * 100 + datepart (iso_week, '2014-01-01');
The result is 201352 for the first date and 201401 for the second date.
However, this is not the expected result because...
2014-01-01 belongs to the last week of 2013
So the expected result is 201352
Do any of you more experienced T-SQL developers know how to extract the year/week of a given date and have this match what I see in MySQL?
I need to have the week start on Monday. This is why I am using iso_week. I have tested the results with week anyway and found the same issue. This query also produces 201401 when 201352 is expected.
SELECT datepart(year, '2014-01-01') * 100 + datepart (week, '2014-01-01');
If you look at the ISO_Week datepart definition at http://msdn.microsoft.com/en-us/library/ms174420.aspx, you'll see the following:
ISO 8601 includes the ISO week-date system, a numbering system for
weeks. Each week is associated with the year in which Thursday
occurs...
The numbering system in different countries/regions might not comply
with the ISO standard.
Since January 1, 2014 was a Wednesday; January 2, 2014 was the first Thursday of the year and thus week 1 of 2014 (according to ISO 8601).
Furthermore, looking at the MySQL definitions for yearweek and week, there are several mode options (http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_week)
So, I think you're going to have to write your own yearweek function for the week counting rule you want:
CREATE FUNCTION dbo.yearweek(#date date)
RETURNS INT
as
begin
set #date = dateadd(dd,-datepart(dw,#date)+1, #date)
return datepart(year,#date)*100 + datepart(week,#date)
end
go
select dbo.yearweek('2013-12-31'), dbo.yearweek('2014-01-01')
NOTE: I haven't fully tested this code, and I'm not sure exactly what your requirements are. This is just meant as an example of the type of process you need to follow.
I think it's because you're using "ISO_WEEK" as the datepart
Look at the description under the "ISO_WEEK datepart" here: http://msdn.microsoft.com/en-us/library/ms174420.aspx
using "WEEK" instead might get the desired result
TO extract YEAR, MONTH or DAY you can simply use the YEAR, MONTH and DAY function as shown in the followinf example. for any other part you have to use the DATEPART function , read here for a detailed list of arguements you can pass to DATEPART function.
SELECT YEAR(GETDATE()) AS [YEAR]
, DATEPART(WEEK, GETDATE()) [Week]
UPDATE
SELECT CAST(YEAR(GETDATE()) AS VARCHAR(4)) +'-'
+ CAST(DATEPART(WEEK, GETDATE()) AS VARCHAR(2))
It seems to me that what you want is a week number based on the previous Monday. Is this correct? If so, iso_week is no use to you as it is based on this week's Thursday.
To get the year and week based on the previous Monday, I think you need something like the following.
set datefirst 1 ;
select
SomeDate ,
datename( weekday, SomeDate ) as [WeekdayName] ,
datepart( weekday, SomeDate ) as [Weekday] ,
datepart( week, SomeDate ) as [Week] ,
datepart( iso_week, SomeDate ) as [ISO_week] ,
dateadd( day, -( datepart( weekday, SomeDate ) - 1 ), SomeDate ) as [PreviousMonday] ,
datepart( year, dateadd( day, -( datepart( weekday, SomeDate ) - 1 ), SomeDate ) ) as [MondayYear] ,
datepart( week, dateadd( day, -( datepart( weekday, SomeDate ) - 1 ), SomeDate ) ) as [MondayWeek]
from
dbo.DateDemo
order by
SomeDate ;
Abbreviated sample output is as follows.
SomeDate PreviousMonday MondayYear MondayWeek
2013-12-25 2013-12-23 2013 52
2013-12-26 2013-12-23 2013 52
2013-12-27 2013-12-23 2013 52
2013-12-28 2013-12-23 2013 52
2013-12-29 2013-12-23 2013 52
2013-12-30 2013-12-30 2013 53
2013-12-31 2013-12-30 2013 53
2014-01-01 2013-12-30 2013 53
2014-01-02 2013-12-30 2013 53
2014-01-03 2013-12-30 2013 53
2014-01-04 2013-12-30 2013 53
2014-01-05 2013-12-30 2013 53
2014-01-06 2014-01-06 2014 2
In T-SQL what is the best way to convert a month name into a number?
E.g:
'January' -> 1
'February' -> 2
'March' -> 3
Etc.
Are there any built in functions that can do this?
How about this?
select DATEPART(MM,'january 01 2011') -- returns 1
select DATEPART(MM,'march 01 2011') -- returns 3
select DATEPART(MM,'august 01 2011') -- returns 8
How about this:
SELECT MONTH('March' + ' 1 2014')
Would return 3.
Its quit simple,
Take the first 3 digits of the month name and use this formula.
Select charindex('DEC','JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC')/4+1
SELECT DATEPART(MM,'january '+'01 1900')
SELECT MONTH('january ' + '01 1900')
SELECT month(dateadd(month,DATEDIFF(month,0,'january 01 2015'),0))
You can create a function and then refer to it in the select statement.
The function may look similar to this:
if OBJECT_ID('fn_month_name_to_number', 'IF') is not null
drop function fn_month_name_to_number
go
create function fn_month_name_to_number (#monthname varchar(25))
returns int as
begin
declare #monthno as int;
select #monthno =
case #monthname
when 'January' then 1
when 'February' then 2
when 'March' then 3
when 'April' then 4
when 'May' then 5
when 'June' then 6
when 'July' then 7
when 'August' then 8
when 'September' then 9
when 'October' then 10
when 'November' then 11
when 'December' then 12
end
return #monthno
end
Then you can query it.
select fn_month_name_to_number ('February') as month_no
This query will return 2 as month number.
You can pass values from a column as parameters to the function.
select fn_month_name_to_number (*columnname*) as month_no from *tablename*
Have a good day!
There is no built in function for this.
You could use a CASE statement:
CASE WHEN MonthName= 'January' THEN 1
WHEN MonthName = 'February' THEN 2
...
WHEN MonthName = 'December' TNEN 12
END AS MonthNumber
or create a lookup table to join against
CREATE TABLE Months (
MonthName VARCHAR(20),
MonthNumber INT
);
INSERT INTO Months
(MonthName, MonthNumber)
SELECT 'January', 1
UNION ALL
SELECT 'February', 2
UNION ALL
...
SELECT 'December', 12;
SELECT t.MonthName, m.MonthNumber
FROM YourTable t
INNER JOIN Months m
ON t.MonthName = m.MonthName;
I recently had a similar experience (sql server 2012). I did not have the luxury of controlling the input, I just had a requirement to report on it. Luckily the dates were entered with leading 3 character alpha month abbreviations, so this made it simple & quick:
TRY_CONVERT(DATETIME,REPLACE(obs.DateValueText,SUBSTRING(obs.DateValueText,1,3),CHARINDEX(SUBSTRING(obs.DateValueText,1,3),'...JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC')/4))
It worked for 12 hour:
Feb-14-2015 5:00:00 PM 2015-02-14 17:00:00.000
and 24 hour times:
Sep-27-2013 22:45 2013-09-27 22:45:00.000
(thanks ryanyuyu)
I think you may even have a separate table like a monthdetails (Monthno int, monthnames char(15)) and include values:
1 January
2 February
.... and so on, and then join this table with your existing table in the monthnames column
SELECT t1.*,t2.Monthno from table1
left outer join monthdetails t2
on t1.monthname=t2.monthnames
order by t2.Monthno
You can use below code
DECLARE #T TABLE ([Month] VARCHAR(20))
INSERT INTO #T
SELECT 'January'
UNION
SELECT 'February'
UNION
SELECT 'March'`
SELECT MONTH('01-' + [Month] + '-2010') As MonthNumeric,[Month] FROM #T
ORDER BY MonthNumeric
You can try sth like this, if you have month_name which is string datetype.After converting, you can feel free to order by Month.
For example, your table like this:
month
Dec
Jan
Feb
Nov
Mar
.
.
.
My syntax is:
Month(cast(month+'1 2016' as datetime))
You can do it this way, if you have the date (e.g. SubmittedDate)
DATENAME(MONTH,DATEADD(MONTH, MONTH(SubmittedDate) - 1, 0)) AS ColumnDisplayMonth
Or you can do it this way, if you have the month as an int
DATENAME(MONTH,DATEADD(MONTH, #monthInt - 1, 0)) AS ColumnDisplayMonth
I know this may be a bit too late but the most efficient way of doing this through a CTE as follows:
WITH Months AS
(
SELECT 1 x
UNION all
SELECT x + 1
FROM Months
WHERE x < 12
)
SELECT x AS MonthNumber, DateName( month , DateAdd( month , x , -1 )) AS MonthName FROM Months
try this
SELECT EXTRACT(MONTH FROM TO_DATE(month_added, 'Month')) AS month_number
select Convert(datetime, '01 ' + Replace('OCT-12', '-', ' '),6)