Combining two rows in one select query - sql

Hi I am having a hard time combining two records (from a single table) on a single query. The idea is, DATE_FIELD column is a date type and ColA is an integer data type.
To further illustrate my inquiry, I have attached an image below
1.) Is the raw table.
2.) Is the desired output.
P.S. The filter for DATE_FIELD is not a simple "WHERE DATE_FIELD IN" clause.
For example, I wanted to get the DATE_FIELD=12/30/2013. Then I need to get the Previous Sept DATE_FIELD also, which is 9/30/2013 programatically by using this query that I got from the web:
CASE
WHEN MONTH(DATE_FIELD) < 10
THEN
(cast(CAST((DATE_FIELD) - 1) as char(4)) + RIGHT('00' + LTRIM(09),2) + RIGHT('00' + LTRIM(30),2) AS Date))
ELSE
( cast(CAST((YEAR(DATE_FIELD)) as char(4)) + RIGHT('00' + LTRIM(09),2) + RIGHT('00' + LTRIM(30),2) AS Date))
END
Here is my current sql script (which cannot get the ColA equivalent for Previous Sept filter:
SELECT DATE_FIELD, ColA,
CASE
WHEN MONTH(DATE_FIELD) < 10
THEN
(cast(CAST((YEAR(DATE_FIELD) - 1) as char(4)) + RIGHT('00' + LTRIM(09),2) + RIGHT('00' + LTRIM(30),2) AS Date))
ELSE
( cast(CAST((YEAR(DATE_FIELD)) as char(4)) + RIGHT('00' + LTRIM(09),2) + RIGHT('00' + LTRIM(30),2) AS Date))
END AS PREVIOUS,
(
SELECT ColA
FROM TABLE_A
WHERE DATE_FIELD =
CASE
WHEN MONTH(DATE_FIELD) < 10
THEN
(cast(CAST((YEAR(DATE_FIELD) - 1) as char(4)) + RIGHT('00' + LTRIM(09),2) + RIGHT('00' + LTRIM(30),2) AS Date))
ELSE
( cast(CAST((YEAR(DATE_FIELD)) as char(4)) + RIGHT('00' + LTRIM(09),2) + RIGHT('00' + LTRIM(30),2) AS Date))
END
) AS PYE_colA
FROM TABLE_A
WHERE DATE_FIELD = '12/30/2013'
Thanks!

Do a cross join with the same table and use your CASE structure only in the where clause:
SELECT a.DATE_FIELD AS DATE_FIELD_1,
a.ColA AS ColA_1,
b.DATE_FIELD AS DATE_FIELD_2,
b.ColA AS ColA_2
FROM TABLE_A a
CROSS JOIN TABLE_A b
WHERE DATE_FIELD_1 = 'your date'
AND DATE_FIELD_2 = (
CASE
WHEN MONTH(DATE_FIELD_1) < 10
THEN
(cast(CAST((YEAR(DATE_FIELD_1) - 1) as char(4)) + RIGHT('00' + LTRIM(09),2) + RIGHT('00' + LTRIM(30),2) AS Date))
ELSE
( cast(CAST((YEAR(DATE_FIELD_1)) as char(4)) + RIGHT('00' + LTRIM(09),2) + RIGHT('00' + LTRIM(30),2) AS Date))
END)
;
Another possibility based on Thorsten Kettners remarks:
SELECT a.DATE_FIELD AS DATE_FIELD_1,
a.ColA AS ColA_1,
b.DATE_FIELD AS DATE_FIELD_2,
b.ColA AS ColA_2
FROM TABLE_A a
INNER JOIN TABLE_A b
ON b.DATE_FIELD = (
CASE
WHEN MONTH(a.DATE_FIELD) < 10
THEN
(cast(CAST((YEAR(a.DATE_FIELD) - 1) as char(4)) + RIGHT('00' + LTRIM(09),2) + RIGHT('00' + LTRIM(30),2) AS Date))
ELSE
( cast(CAST((YEAR(a.DATE_FIELD)) as char(4)) + RIGHT('00' + LTRIM(09),2) + RIGHT('00' + LTRIM(30),2) AS Date))
END)
WHERE a.DATE_FIELD = 'your date'
;

Related

How do you update Year field in the datetime column using another datetime column?

I have two columns (Birth_date and Purchase_date) and would like to create a column (Birth_date_update) using following conditions
Conditions:
When Birth_date is later than Purchase_date, take birth_date.
When Birth_date is earlier than Purchase_date, Birth_date_update will take the year from purchase_date and override year from birth_date.
If the final value from condition 2 is still earlier than purchase_date, than find next birth_date anniversary that is bigger than purchase date.
Note: Condition 2 and 3 can be summarized as find earliest anniversary of birth_date greater than purchase_date.
Birth_date purchase_date Birth_date_update
2002-02-21 2006-05-11 2007-02-21
2004-01-18 2004-01-25 2005-01-18
2011-07-24 2011-04-09 2011-07-24
2006-12-16 2007-10-08 2007-12-16
2007-04-30 2008-03-14 2008-04-30
I have no idea how to code this.. please help!
update my_table
set birth_date_update = case
when birth_date > purchase_date then birth_date -- Condition 1
when birth_date < purchase_date then dateadd(year, datediff(year, birth_date, purchase_date), birth_date) -- Condition 2
when dateadd(year, datediff(year, birth_date, purchase_date), purchase_date) < purchase_date
then dateadd(year, 1, dateadd(year, datediff(year, birth_date, purchase_date), purchase_date)) end -- Condition 3
Result from above answer doesn't seem to be correct. Looks like Condition 3 is not working consistent. So I added my answer
create table TAB1 (BD date, PD date, BDU date)
insert into TAB1 values
('2002-02-21', '2006-05-11', NULL),
('2004-01-18', '2004-01-25', NULL),
('2011-07-24', '2011-04-09', NULL),
('2006-12-16', '2007-10-08', NULL),
('2007-04-30', '2008-03-14', NULL)
;with cc as (
select BD, PD,
case
when BD > PD then BD
when BD < PD then cast(cast(year(PD) as varchar) + '-' + cast(month(BD) as varchar) + '-' + cast(day(BD) as varchar) as date)
end as BDU
from TAB1
)
, cc2 as (
select BD, PD,
case
when BDU < PD then dateadd(day, 365, BDU)
else BDU
end as BDU
from cc
)
update T1
set BDU = cc2.BDU
from TAB1 T1
inner join cc2 on cc2.BD = T1.BD and cc2.PD = T1.PD
select * from TAB1
I do not want to be left out of this one. Here is my answer
UPDATE dbo.BirthDateTable SET Birth_date_update =
CASE WHEN Birth_date >= purchase_date THEN Birth_date -- Condition 1
WHEN Birth_date < purchase_date
THEN CASE
WHEN CONVERT(Date , CAST( DATEPART(YEAR,purchase_date) AS Varchar(4)) + '-' + CAST(DATEPART(MONTH,Birth_date) AS Varchar(2)) + '-' + CAST(DATEPART(DAY, Birth_date) AS Varchar(2))) > purchase_date
THEN CONVERT(Date , CAST( DATEPART(YEAR,purchase_date) AS Varchar(4)) + '-' + CAST(DATEPART(MONTH,Birth_date) AS Varchar(2)) + '-' + CAST(DATEPART(DAY, Birth_date) AS Varchar(2))) -- Condition 2
ELSE DATEADD(YEAR,1,CONVERT(Date , CAST( DATEPART(YEAR,purchase_date ) AS Varchar(4)) + '-' + CAST(DATEPART(MONTH,Birth_date) AS Varchar(2)) + '-' + CAST(DATEPART(DAY, Birth_date) AS Varchar(2)))) -- Condition 3
END
END
Here is a select example.
SELECT
CASE WHEN Birth_date >= purchase_date THEN Birth_date -- Condition 1
WHEN Birth_date < purchase_date
THEN CASE
WHEN CONVERT(Date , CAST( DATEPART(YEAR,purchase_date) AS Varchar(4)) + '-' + CAST(DATEPART(MONTH,Birth_date) AS Varchar(2)) + '-' + CAST(DATEPART(DAY, Birth_date) AS Varchar(2))) > purchase_date
THEN CONVERT(Date , CAST( DATEPART(YEAR,purchase_date) AS Varchar(4)) + '-' + CAST(DATEPART(MONTH,Birth_date) AS Varchar(2)) + '-' + CAST(DATEPART(DAY, Birth_date) AS Varchar(2))) -- Condition 2
ELSE DATEADD(YEAR,1,CONVERT(Date , CAST( DATEPART(YEAR,purchase_date ) AS Varchar(4)) + '-' + CAST(DATEPART(MONTH,Birth_date) AS Varchar(2)) + '-' + CAST(DATEPART(DAY, Birth_date) AS Varchar(2)))) -- Condition 3
END
END
FROM dbo.BirthDateTable
Other post about above answer not being correct was written when the order of the answers was different on the page. I believe this answer meets the criteria.#JamieHong, could you see if this select works on your system? I padded the month and day with zeros.
SELECT
CASE WHEN Birth_date >= purchase_date THEN Birth_date
WHEN Birth_date < purchase_date
THEN CASE
WHEN CONVERT(Date , CAST( DATEPART(YEAR,purchase_date) AS Varchar(4)) + '-' + RIGHT('00' + CAST(DATEPART(MONTH,Birth_date) AS Varchar(2)),2) + '-' + RIGHT('00' + CAST(DATEPART(DAY, Birth_date) AS Varchar(2)),2)) > purchase_date
THEN CONVERT(Date , CAST( DATEPART(YEAR,purchase_date) AS Varchar(4)) + '-' + RIGHT('00' + CAST(DATEPART(MONTH,Birth_date) AS Varchar(2)),2) + '-' + RIGHT('00' + CAST(DATEPART(DAY, Birth_date) AS Varchar(2)),2))
ELSE DATEADD(YEAR,1,CONVERT(Date , CAST( DATEPART(YEAR,purchase_date ) AS Varchar(4)) + '-' + RIGHT('00' + CAST(DATEPART(MONTH,Birth_date) AS Varchar(2)),2) + '-' + RIGHT('00' + CAST(DATEPART(DAY, Birth_date) AS Varchar(2)),2)))
END
END AS CalcDate
FROM dbo.BirthDateTable

Query to compare cast in select statement

I have a query where I am pulling in three fields, and converting them to a date. I'm hoping to then run a comparison within the same select statement, but I get an invalid column name on the field I'm attempting to compare. The order by is working correctly though. /scratching_head
SQL Server 2012
SELECT
UTCSID,
UTLCID,
/* put utonmm, utondd, utonyy together as a date called uton */
CAST(
CAST(UTONMM as varchar) + '/' +
CAST(UTONDD as varchar) + '/' +
CASE WHEN UTONCV = '1'
THEN RIGHT('20' + CONVERT(varchar(4), RIGHT('00' + CONVERT(varchar(4), UTONYY),2)),4)
ELSE RIGHT('19' + CONVERT(varchar(4), UTONYY),4)
END
AS DATETIME) AS UTON,
/* put utofmm, utofdd, utofyy together as a date called utoff */
CAST(
CASE WHEN UTOFMM > '0'
THEN
CAST(UTOFMM as varchar) + '/' +
CAST(UTOFDD as varchar) + '/' +
CASE WHEN UTOFCV = '1'
THEN RIGHT('20' + CONVERT(varchar(4), RIGHT('00' + CONVERT(varchar(4), UTOFYY),2)),4)
ELSE RIGHT('19' + CONVERT(varchar(4), UTOFYY),4)
END
END
AS DATETIME) AS UTOFF,
UTCBAL,
UTDBAL,
UTUNPS
FROM [HTEDTA].[THOR].[HTEDTA].UT210AP
WHERE UTLCID = '885570' AND UTOFF > GETDATE() ORDER BY UTON DESC
This statement returns:
Invalid column name: 'UTOFF'
The problem is that the alias utoff isn't known at the time when the where clause is parsed.
One way to get around it is to wrap the query in a common table expression and apply the where clause to that:
WITH CTE AS (
SELECT UTCSID, UTLCID,
/* put utonmm, utondd, utonyy together as a date called uton */
CAST(
CAST(UTONMM as varchar) + '/' +
CAST(UTONDD as varchar) + '/' +
CASE WHEN UTONCV = '1'
THEN RIGHT('20' + CONVERT(varchar(4), RIGHT('00' + CONVERT(varchar(4), UTONYY),2)),4)
ELSE RIGHT('19' + CONVERT(varchar(4), UTONYY),4)
END
AS DATETIME) AS UTON,
/* put utofmm, utofdd, utofyy together as a date called utoff */
CAST(
CASE WHEN UTOFMM > '0'
THEN
CAST(UTOFMM as varchar) + '/' +
CAST(UTOFDD as varchar) + '/' +
CASE WHEN UTOFCV = '1'
THEN RIGHT('20' + CONVERT(varchar(4), RIGHT('00' + CONVERT(varchar(4), UTOFYY),2)),4)
ELSE RIGHT('19' + CONVERT(varchar(4), UTOFYY),4)
END
END
AS DATETIME) AS UTOFF,
UTCBAL, UTDBAL, UTUNPS
FROM [HTEDTA].[THOR].[HTEDTA].UT210AP
)
SELECT *
FROM CTE
WHERE UTLCID = '885570' AND UTOFF > GETDATE()

Concatenating two TIME columns in SQL Server 2012

I want to concatenate two TIME columns and show as one column.
Example:
FromTime: 9:00
ToTime: 12:00
Result should be:
9:00-12:00
Generic SQL:
-- hh:mm:ss
SELECT 'result:' + CONVERT(CHAR(6), FromTime, 8) + '-' + CONVERT(CHAR(6), ToTime)
FROM yourTable
MySQL:
-- hh:mm
SELECT 'result:' + DATE_FORMAT(FromTime, '%H:%i') + '-' + DATE_FORMAT(ToTime, '%H:%i')
FROM yourTable
SQL Server:
-- hh:mm
SELECT 'result:' + convert(char(2), DATEPART(hh, FromTime)) + ':' +
CONVERT(CHAR(2), DATEPART(mm, FromTime)) + '-' +
CONVERT(CHAR(2), DATEPART(hh, ToTime)) + ':' +
CONVERT(CHAR(2), DATEPART(mm, ToTime))
FROM yourTable
declare #FromTime time
declare #ToTime time
set #FromTime='9:00'
set #ToTime='12:00'
select cast(#FromTime as varchar(10))+ '-' + cast(#ToTime as varchar(10)) as result
sql demo
You can use convert
select convert(VARCHAR(5),getdate(),108) + ' - ' + convert(VARCHAR(5),getdate()-1,108)

SQL Query - Have to determine if it is a specific day of the month (ex: 2 Tuesday of month)

I have an app that allows users schedule an action to occur in the future. For example, that can select a date and schedule it to run on that day every month (ex: the 15th of each month). However, I now need to allow them to select a week day and week of the month. For example, they need to run an action the first friday of the month. Therefore I am allowing the to select the weekday (monday, tuesday, wednesday....) and week of the month (1st, 2nd, 3rd, 4th or 5th).
Here is the query I currently use:
Declare #nowString varchar(19)
Declare #nowDateString varchar(19)
Declare #now datetime
Declare #lastMinute datetime
Declare #nowDate datetime
Set #nowString = '#currentDateTime#:00'
Set #nowDateString = LEFT(#nowString, 10)
set #now = #nowString
set #nowDate = DATEADD(dd, 0, DATEDIFF(dd, 0, #now))
set #lastMinute = DATEADD(mi, -1, #now)
select *
from message_prepared
where schedule = '1'
and active = '1'
and noaa = '0'
and (
(
schedule_type = 'recurring'
and startdate <= #nowDate
and isnull(enddate, DATEADD(yy, 1, #nowDate)) >= #nowDate
and (
#nowDateString + ' ' + isnull(recurring_start_time_hour, '00') + ':' + isnull(recurring_start_time_min, '00') + ':00' = #now
or #nowDateString + ' ' + isnull(recurring_start_time_hour, '00') + ':' + isnull(recurring_start_time_min, '00') + ':00' = #lastMinute
)
-- Test for different type of recurring
and (
( ltrim(rtrim(recurring)) = 'M' and DATEPART(dd, startdate) = DATEPART(dd, #now) )
or ( ltrim(rtrim(recurring)) = 'W' and DATEPART(dw, startdate) = DATEPART(dw, #now) )
or ltrim(rtrim(recurring)) = 'D'
)
)
or (
schedule_type = 'once'
and startdate = #nowDate
and (
#nowDateString + ' ' + onetime_start_time_hour + ':' + onetime_start_time_min + ':00' = #now
or #nowDateString + ' ' + onetime_start_time_hour + ':' + onetime_start_time_min + ':00' = #lastMinute
)
)
)
and repeat_multiple_times = 0
UNION ALL
SELECT *
FROM MESSAGE_PREPARED
WHERE schedule = '1'
AND active = 1
AND noaa = 0
AND recurring = 'D'
AND repeat_multiple_times = 1
AND startDate IS NOT NULL
AND recurring_start_time_hour IS NOT NULL
AND recurring_start_time_hour < 24
AND recurring_start_time_min IS NOT NULL
AND recurring_start_time_min < 60
AND startdate <= #nowDate
AND ISNULL(enddate, DATEADD(yy, 1, #nowDate)) >= #nowDate
AND
(
CASE WHEN repeat_unit = 'M'
THEN
DATEDIFF(n,
CONVERT(DATETIME,
CAST(DATEPART(yyyy, startDate) AS VARCHAR(4)) + '-' +
CAST(DATEPART(mm, startDate) AS VARCHAR(2)) + '-' +
CAST(DATEPART(dd, startDate) AS VARCHAR(2)) + ' ' +
CAST(recurring_start_time_hour AS VARCHAR(2)) + ':' +
CAST(recurring_start_time_min AS VARCHAR(2)) + ':00', 20),
GETDATE()) % repeat_interval
ELSE
DATEDIFF(n,
CONVERT(DATETIME,
CAST(DATEPART(yyyy, startDate) AS VARCHAR(4)) + '-' +
CAST(DATEPART(mm, startDate) AS VARCHAR(2)) + '-' +
CAST(DATEPART(dd, startDate) AS VARCHAR(2)) + ' ' +
CAST(recurring_start_time_hour AS VARCHAR(2)) + ':' +
CAST(recurring_start_time_min AS VARCHAR(2)) + ':00', 20),
GETDATE()) % (repeat_interval * 60)
END = 0
OR
CASE WHEN repeat_unit = 'M'
THEN
(DATEDIFF(n,
CONVERT(DATETIME,
CAST(DATEPART(yyyy, startDate) AS VARCHAR(4)) + '-' +
CAST(DATEPART(mm, startDate) AS VARCHAR(2)) + '-' +
CAST(DATEPART(dd, startDate) AS VARCHAR(2)) + ' ' +
CAST(recurring_start_time_hour AS VARCHAR(2)) + ':' +
CAST(recurring_start_time_min AS VARCHAR(2)) + ':00', 20),
GETDATE()) - 1) % repeat_interval
ELSE
(DATEDIFF(n,
CONVERT(DATETIME,
CAST(DATEPART(yyyy, startDate) AS VARCHAR(4)) + '-' +
CAST(DATEPART(mm, startDate) AS VARCHAR(2)) + '-' +
CAST(DATEPART(dd, startDate) AS VARCHAR(2)) + ' ' +
CAST(recurring_start_time_hour AS VARCHAR(2)) + ':' +
CAST(recurring_start_time_min AS VARCHAR(2)) + ':00', 20),
GETDATE()) - 1) % (repeat_interval * 60)
END = 0
)
This will only occur when reocurring is set to "M" and I would like to determine if today is the specific day of the week, week of the month and hour/min.
This is pretty simple logic. Today is the nth DOW of the month when the following is true:
Today is that day of the week
The day of the month is between 7*(n-1) + 1 and 7 * n
So, the first Monday of the month is always between the 1st and 7th, and so on. Here is an example case statement to test this:
declare #DayOfWeek varchar(255) = 'Thursday';
declare #Which int = 3;
select (case when datename(dw, Today) = #DayOfWeek and
(DAY(Today) - 1) / 7 = #Which - 1
then 1
else 0
end)
from (select CAST(getdate() as date) as Today) t
I've structured the query this way so you can test it with different values. Just replace the expression that defines Today, with something like getdate() - 3 or '2013-01-01'.

How to convert date into DD-MON-YYYY HH24:MI:SS format?

Can someone help me with SQL Date format?
The following statement
SELECT convert(VARCHAR(20),GETDATE(),113)
returns
04 Aug 2011 08:08:08.
I want the results like
Aug-04-2011 08:08:08
Thank you!
SELECT
LEFT(DATENAME(MONTH, Date), 3) + '-' +
RIGHT(100 + DAY(Date), 2) + '-' +
DATENAME(YEAR, Date) + ' ' +
CONVERT(varchar, Date, 108)
FROM (SELECT Date = GETDATE()) s
Off the top of my head, I think its:
SELECT convert(VARCHAR(20),GETDATE(),120)
EDIT:
This will work:
SELECT datename(day, GETDATE()) + '-'
+ substring(datename(month, GETDATE()),0,4) + '-'
+ datename(year, GETDATE()) + ' '
+ datename(hh, GETDATE()) + ':'
+ datename(mi, GETDATE()) + ':'
+ datename(ss, GETDATE())
SECOND EDIT:
SELECT substring(datename(month, GETDATE()),0,4) + '-'
+ datename(day, GETDATE()) + '-'
+ datename(year, GETDATE()) + ' '
+ datename(hh, GETDATE()) + ':'
+ datename(mi, GETDATE()) + ':'
+ datename(ss, GETDATE())
THIRD EDIT:
select substring(datename(month, GETDATE()),0,4) + '-'
+ right(datename(day, GETDATE())+100,2) + '-'
+ datename(year, GETDATE()) + ' '
+ right(datename(hh, GETDATE())+100,2) + ':'
+ right(datename(mi, GETDATE())+100,2) + ':'
+ right(datename(ss, GETDATE())+100,2)
The built-in convert won't allow you to format your date exactly as you desire, unfortunately.
With a little manipulation, you can get there though:
SELECT stuff(stuff(convert(VARCHAR(20),GETDATE(),113), 3, 1, '-'), 7, 1, '-')
You could put this in a UDF and call that whenever you want your date formatted in this manner.