Sorting in SQL Server by two columns - sql-server

I have an employee table with below details
EMPid TimeIn. TimeOut
---------------------------------------------
123 1 Jan 2016 10:10 NULL
123 NULL 1 Jan 2016 18:30
123 1 Jan 2016 9:10 NULL
123 NULL 1 Jan 2016 18:00
I need output with order by time in ascending order. Below is sample output.
EMPid TimeIn. TimeOut
------------------------------------------------
123 1 Jan 2016 9:10 NULL
123 1 Jan 2016 10:10 NULL
123 NULL 1 Jan 2016 18:00
123 NULL 1 Jan 2016 18:30

SELECT * FROM Employee ORDER BY TimeIn, TimeOut

Try this,
DECLARE #employee TABLE (EMPid INT,TimeIn DATETIME,TimeOut DATETIME)
INSERT INTO #employee(EMPid,TimeIn,TimeOut)
VALUES(123,' 1 Jan 2016 10:10', NULL),
(123,NULL, '1 Jan 2016 18:30'),
(123,' 1 Jan 2016 9:10' , NULL),
(123, NULL , '1 Jan 2016 18:00')
SELECT * FROM #employee ORDER BY ISNULL(TimeIn,TimeOut)

Related

Break Quarter into Months in SQL Server

I want to break the quarters into months. In source I have 2019Q1 but I need to break the one record into 3 records
empid Quarter earnings
-----------------------
123 2019Q1 4000
456 2019Q2 6000
Desired result:
mpid Month earnings
---------------------------
123 January 2019 4000
123 February 2019 4000
123 March 2019 4000
456 April 2019 6000
456 May 2019 6000
456 June 2019 6000
As Larnu suggested, a Calendar Table is well worth the effort. That said, here is an option that performs a 1-to-many join to an ad-hoc table
Example
Select empid
,MonthYear = datename(month,datefromparts(left(Quarter,4),MM,1))+' '+left(Quarter,4)
,Earnings
From YourTable A
Join (
Select *
From ( values (1,1)
,(1,2)
,(1,3)
,(2,4)
,(2,5)
,(2,6)
,(3,7)
,(3,8)
,(3,9)
,(4,10)
,(4,11)
,(4,12)
)B1(QQ,MM)
) B on right(Quarter,1)=QQ
Results
empid MonthYear Earnings
123 January 2019 4000
123 February 2019 4000
123 March 2019 4000
456 April 2019 6000
456 May 2019 6000
456 June 2019 6000
If you don't need the "earnings" value by month, then you just need to setup a CTE to match the Q# with the corresponding months and add that to your query.

Oracle - Cycle detected while executing recursive 'WITH' query

I'm doing a basic example of recursive query with oracle sql. I'm computing future months of the format MON-YY. I managed to have a seemingly correct query but I don't understand the break condition with a WITH query.
I'm trying to break on the year value (for example stop when you reach 2020), but it detects a cycle while doing that. If I break on the month value (e.g. December), it works.
Here's my query with a month based break:
with
prochains_mois(mois, annee) as (
select 'sep' as mois, 19 as annee
from dual
union all
select
case mois
when 'jan' then 'fev'
when 'fev' then 'mar'
when 'mar' then 'avr'
when 'avr' then 'mai'
when 'mai' then 'jun'
when 'jun' then 'jui'
when 'jui' then 'aou'
when 'aou' then 'sep'
when 'sep' then 'oct'
when 'oct' then 'nov'
when 'nov' then 'dec'
when 'dec' then 'jan'
end,
case mois
when 'dec' then annee + 1
else annee
end
from prochains_mois r
where mois <> 'dec'
)
select * from prochains_mois;
If I do this, it returns a consistent result.
MOI ANNEE
--- ----------
sep 19
oct 19
nov 19
dec 19
Now if I try to break the recursive query on the year, let's say 2020, so I change the where condition in the with clause to :
where annee < 20
Then I get :
ORA-32044: cycle detected while executing recursive WITH query
I tried to break with a later month to see if my year addition works correctly, it seems to be the case. If I break on march, I get the January and February correctly :
where mois <> 'mar'
gives
MOI ANNEE
--- ----------
sep 19
oct 19
nov 19
dec 19
jan 20
fev 20
mar 20
Use DATEs:
with prochains_mois( value ) as (
select DATE '2019-09-01' from dual
union all
select ADD_MONTHS( value, 1 )
FROM prochains_mois
WHERE value < DATE '2020-12-01'
)
select SUBSTR( TO_CHAR( value, 'mon', 'NLS_DATE_LANGUAGE=FRENCH' ), 1, 3 ) AS mois,
TO_CHAR( value, 'RR' ) AS annee
from prochains_mois;
Output:
MOIS | ANNEE
:--- | :----
sep | 19
oct | 19
nov | 19
dec | 19
jan | 20
fev | 20
mar | 20
avr | 20
mai | 20
jui | 20
jui | 20
aou | 20
sep | 20
oct | 20
nov | 20
dec | 20
or use your query and check that the month and year do not match:
with
prochains_mois(mois, annee) as (
select 'sep' as mois, 19 as annee
from dual
union all
select
case mois
when 'jan' then 'fev'
when 'fev' then 'mar'
when 'mar' then 'avr'
when 'avr' then 'mai'
when 'mai' then 'jun'
when 'jun' then 'jui'
when 'jui' then 'aou'
when 'aou' then 'sep'
when 'sep' then 'oct'
when 'oct' then 'nov'
when 'nov' then 'dec'
when 'dec' then 'jan'
end,
case mois
when 'dec' then annee + 1
else annee
end
from prochains_mois r
where ( mois, annee ) NOT IN ( ( 'dec', 20 ) )
)
select * from prochains_mois;
Output:
MOIS | ANNEE
:--- | ----:
sep | 19
oct | 19
nov | 19
dec | 19
jan | 20
fev | 20
mar | 20
avr | 20
mai | 20
jun | 20
jui | 20
aou | 20
sep | 20
oct | 20
nov | 20
dec | 20
db<>fiddle here
Your main issue is that you're trying to manipulate dates using strings/numbers. Don't do that; if you're working with dates, use dates!
E.g. you can do what you're after like so:
WITH prochains_mois (mnth_dt) AS (SELECT TRUNC(sysdate, 'mm') mnth_dt
FROM dual
UNION ALL
SELECT add_months(mnth_dt, 1) mnth_dt
FROM prochains_mois
WHERE add_months(mnth_dt, 1) < add_months(TRUNC(sysdate, 'yyyy'), 12))
SELECT mnth_dt,
to_char(mnth_dt, 'mon') mois,
to_char(mnth_dt, 'yy') annee
FROM prochains_mois;
MNTH_DT MOIS ANNEE
----------- ---- -----
01/09/2019 sep 19
01/10/2019 oct 19
01/11/2019 nov 19
01/12/2019 dec 19
N.B. You could simplify the predicate in the recursive sub-factored query to mnth_dt < add_months(TRUNC(SYSDATE, 'yyyy'), 11).
This works by taking the start date (here, I've used sysdate) and finding the first of the month (by using the optional second parameter of TRUNC to specify the level we're truncating it to).
Then we simply add a month to each date until we hit the last month of the start date's year.
Only after you've got the dates do you then output the data in the format you require using to_char.

Count Consecutive Days where value greater than 0

Using SQL Server 2012, I am trying create a query that provides me with, say, the top 10 longest wet (or dry) periods from a climate database.
My temp table provides the following data output:
select monthid as [id], date, rain_today
from #raindays
order by monthid asc, date asc
Output:
id date rain_today
-------------------------------
1 24 Dec 2014 2.4
1 25 Dec 2014 0
1 26 Dec 2014 8.7
1 27 Dec 2014 1.8
1 28 Dec 2014 0.3
1 29 Dec 2014 0
1 30 Dec 2014 0
1 31 Dec 2014 0.3
2 01 Jan 2015 0.3
2 02 Jan 2015 0.3
2 03 Jan 2015 18.3
2 04 Jan 2015 0.3
etc. etc.
I would like to return a ranked table that would count the period where rain_today is > 0, (or rain_today = 0) i.e:
Rank Start_Date End_Date Wet Period
----------------------------------------
1 31 Dec 2014 04 Jan 2015 5
2 26 Dec 2014 28 Dec 2014 3
...
The closest I have got from reviewing other similar queries is the following (this is for dry days):
select
#raindays.monthid as id,
min(#raindays.date) as [FirstDryDay],
max(#raindays.date) as [LatestDryDay],
count(*) as countdays
from
(select
monthid,
coalesce(max(case
when rain_today > '0'
then #raindays.date end), '19000101') as latestdry
from
#raindays
group by
monthid) g
join
#raindays on #raindays.monthid = g.monthid
and #raindays.date > g.latestdry
group by
#raindays.monthid
order by
countdays desc
Output:
id FirstDryDay LatestDryDay countdays
-----------------------------------------------
23 21 Oct 2016 31 Oct 2016 11
21 23 Aug 2016 31 Aug 2016 9
**15 23 Feb 2016 29 Feb 2016 7**
10 25 Sep 2015 30 Sep 2015 6
8 28 Jul 2015 31 Jul 2015 4
24 28 Nov 2016 30 Nov 2016 3
29 29 Apr 2017 30 Apr 2017 2
30 30 May 2017 31 May 2017 2
31 29 Jun 2017 30 Jun 2017 2
20 30 Jul 2016 31 Jul 2016 2
7 29 Jun 2015 30 Jun 2015 2
5 30 Apr 2015 30 Apr 2015 1
11 31 Oct 2015 31 Oct 2015 1
17 30 Apr 2016 30 Apr 2016 1
22 30 Sep 2016 30 Sep 2016 1
As you can see, I don't really want to group by id as I want to be able to span over different months and I'm missing other periods that occur earlier in the month. The actual count is working fine correctly it seems, checking above highlighted period:
id date rain_today
15 22 Feb 2016 3.9
15 23 Feb 2016 0
15 24 Feb 2016 0
15 25 Feb 2016 0
15 26 Feb 2016 0
15 27 Feb 2016 0
15 28 Feb 2016 0
15 29 Feb 2016 0
16 01 Mar 2016 3
Thanks in advance for any help!
Is this what you want???
IF OBJECT_ID('tempdb..#TestData', 'U') IS NOT NULL
DROP TABLE #TestData;
CREATE TABLE #TestData (
id INT NOT NULL ,
[Date] DATE NOT NULL,
Rain_Today DECIMAL(9,2) NOT NULL
);
INSERT #TestData (id, Date, Rain_Today) VALUES
(1, '24 Dec 2014', 2.4),
(1, '25 Dec 2014', 0),
(1, '26 Dec 2014', 8.7),
(1, '27 Dec 2014', 1.8),
(1, '28 Dec 2014', 0.3),
(1, '29 Dec 2014', 0),
(1, '30 Dec 2014', 0),
(1, '31 Dec 2014', 0.3),
(2, '01 Jan 2015', 0.3),
(2, '02 Jan 2015', 0.3),
(2, '03 Jan 2015', 18.3),
(2, '04 Jan 2015', 0.3);
--======================================
WITH
cte_AddRankGroup AS (
SELECT
td.id,
td.Date,
td.Rain_Today,
hr.HasRain,
RankGroup = DENSE_RANK() OVER (PARTITION BY td.id ORDER BY td.Date) -
DENSE_RANK() OVER (PARTITION BY td.id, hr.HasRain ORDER BY td.Date)
FROM
#TestData td
CROSS APPLY ( VALUES (IIF(td.Rain_Today = 0, 0, 1)) ) hr (HasRain)
)
SELECT
arg.id,
BegDate = MIN(arg.Date),
EndDate = MAX(arg.Date),
WetPeriod = IIF(arg.HasRain = 1, 'Wet', 'Dry'),
ConsecutiveDays = COUNT(1)
FROM
cte_AddRankGroup arg
GROUP BY
arg.id,
arg.HasRain,
arg.RankGroup
ORDER BY
arg.id,
MIN(arg.Date);
Results...
id BegDate EndDate WetPeriod ConsecutiveDays
----------- ---------- ---------- --------- ---------------
1 2014-12-24 2014-12-24 Wet 1
1 2014-12-25 2014-12-25 Dry 1
1 2014-12-26 2014-12-28 Wet 3
1 2014-12-29 2014-12-30 Dry 2
1 2014-12-31 2014-12-31 Wet 1
2 2015-01-01 2015-01-04 Wet 4
Edit: Code version using CASE expression in place of IIF...
--======================================
WITH
cte_AddRankGroup AS (
SELECT
td.id,
td.Date,
td.Rain_Today,
hr.HasRain,
RankGroup = DENSE_RANK() OVER (PARTITION BY td.id ORDER BY td.Date) -
DENSE_RANK() OVER (PARTITION BY td.id, hr.HasRain ORDER BY td.Date)
FROM
#TestData td
CROSS APPLY ( VALUES (CASE WHEN td.Rain_Today = 0 THEN 0 ELSE 1 END) ) hr (HasRain)
)
SELECT top 10
arg.id,
BegDate = MIN(arg.Date),
EndDate = MAX(arg.Date),
WetPeriod = CASE WHEN arg.HasRain = 1 THEN 'Wet' ELSE 'Dry' END,
ConsecutiveDays = COUNT(1)
FROM
cte_AddRankGroup arg
WHERE
arg.HasRain = '0' -- Top 10 Dry
--arg.HasRain = '1' -- Top 10 Wet
GROUP BY
arg.id,
arg.HasRain,
arg.RankGroup
ORDER BY
ConsecutiveDays desc, MIN(arg.Date);
Modified original script to produce the Top 10 by each period type which was my ultimate aim (output is from the full dataset):
id BegDate EndDate WetPeriod ConsecutiveDays
31 10 Jun 2017 26 Jun 2017 Dry 17
4 02 Mar 2015 14 Mar 2015 Dry 13
5 12 Apr 2015 24 Apr 2015 Dry 13
20 15 Jul 2016 26 Jul 2016 Dry 12
29 01 Apr 2017 11 Apr 2017 Dry 11
26 17 Jan 2017 27 Jan 2017 Dry 11
23 21 Oct 2016 31 Oct 2016 Dry 11
25 01 Dec 2016 09 Dec 2016 Dry 9
21 10 Aug 2016 18 Aug 2016 Dry 9
21 23 Aug 2016 31 Aug 2016 Dry 9
This problem can be resolved by recursion in this way:
-- this variable is needed to stop the recursion
declare #numrows int=(select count(1) from #raindays)
-- add a row number to the table creating a new table as "tabseq"
;WITH tabseq as (select row_number() over(order by date) as rownum, * from #raindays),
-- apply recursion to tabseq keeping a toggle running totals of wet and dry periods
CTE as
(
select *,
(case when rain_today=0 then 1 else 0 end) as dry,
(case when rain_today>0 then 1 else 0 end) as wet
from tabseq where rownum=1
union all
select s.*,
(case when s.rain_today=0 then cte.dry+1 else 0 end) as dry,
(case when s.rain_today>0 then cte.wet+1 else 0 end) as wet
from tabseq s
join cte on s.rownum=cte.rownum+1
where s.rownum<=#numrows
)
select * from cte
Once you have the table (cte) with the dry/wet accumulators you can order and select from it to suit your output requirements.
Please note that this is assuming consecutive days on the table, if there are gaps then instead of adding +1 on the case statement you may need to add a datediff to one side or the other depending how you consider the missing dates (wet or dry).

How do I get sorted dates using union on multiple select statements?

SELECT ITEM, TXNDate, RIGHT(CONVERT(VARCHAR(10),PREVDATE,6),7), RIGHT(CONVERT(VARCHAR(10),DATEADD(year,1,NEXTVDATE),6),7) FROM TABLE
this retrieves as below
-------------------------------------------
ITEM | TXNDate |PREVDATE | NEXTDATE |
-------------------------------------------
item-A 03 Jan 13 Jan 13 Jan 14
item-C 06 Jan 13 Jan 13 Jan 14
item-B 08 Jan 13 Jan 13 Jan 14
item-A 05 Feb 13 Feb 13 Feb 14
item-B 07 Feb 13 Feb 13 Feb 14
item-B 16 Mar 13 Mar 13 Mar 14
item-A 03 Apr 13 Apr 13 Apr 14
_______________________________________
Here I'm trying to show dates in Ordered manner
SELECT * INTO #DATES FROM (SELECT PREVDATE DATES from #DATA
UNION
SELECT NEXTDATE DATES from #DATA) p
SELECT * FROM #DATES
But I'm getting this result
----------
| DATES |
----------
Apr 13
Apr 14
Feb 13
Feb 14
Jan 13
Jan 14
Mar 13
Mar 14
---------
Please help me to get result as
----------
| DATES |
----------
Jan 13
Jan 14
Feb 13
Feb 14
Mar 13
Mar 14
Apr 13
Apr 14
---------
You can just add ORDER BY to your last SELECT to get the dates in an ascending order:
SELECT * INTO #DATES FROM (SELECT PREVDATE DATES from #DATA
UNION
SELECT NEXTDATE DATES from #DATA) p
SELECT * FROM #DATES
ORDER BY DATEPART(MONTH, CONVERT(DATE, '01 ' + DATES)),
DATEPART(YEAR, CONVERT(DATE, '01 ' + DATES))
As your dates are strings, you need to convert them to dates. Then get the month and year parts as this is the order you want.
The ordering you want in your result is a little strange, because you want Jan 14 to be before Feb 13?
Without an ORDER BY clause you will never be certain of the way the records are ordered. Including this clause is therefore necessary, as explained here
SELECT * INTO #DATES FROM
(SELECT PREVDATE DATES from #DATA
UNION
SELECT NEXTDATE DATES from #DATA
) p
SELECT *
FROM #DATES
ORDER BY DATES

sql server - help in query

I have a table called employee_salary_master in which we keep salary effective dates and entry dates of each employee in the company.
For processing salary of an employee for a month, we need to fetch most recently entered record. If the effective date is less than
that month then we pick the most recent entry. but if effective date is greater than the first date of the month, then there will be more than
one effective dates for that month
example: the data for an employee is as below.
SAL_MATSER_ID EMPLOYEE_ID EFFECTIVE_DATE ENTRY_DATE
------------- ----------- -------------- ------------
1 5814 Jan 6 2006 Jan 12 2006
2 5814 Jan 10 2006 Jul 17 2006
3 5814 Jan 20 2006 Dec 22 2006
4 5814 May 10 2007 Jul 18 2007
5 5814 Nov 1 2007 Dec 18 2007
6 5814 Aug 1 2008 Aug 20 2008
7 5814 May 1 2008 Sep 2 2008
8 5814 Sep 1 2009 Sep 18 2008
9 5814 Nov 1 2008 Apr 20 2009
10 5814 Nov 10 2009 Nov 25 2009
11 5814 Nov 5 2009 Nov 26 2009
If i need to get the record for Nov 2009, I write the query below
select EMPLOYEE_SALARY_MASTER_ID, EMPLOYEE_ID, EFFECTIVE_DATE, ENTRY_DATE, ARREAR_PROCESS_FLAG from employee_salary_master esm where employee_id = 5814
and (esm.entry_date = (select max(entry_date) from employee_salary_master where employee_id = 5814 and effective_date <= #monthfirstdate)
or (esm.effective_date between #monthfirstdate and #monthlastdate))
which gives the result below..
SAL_MATSER_ID EMPLOYEE_ID EFFECTIVE_DATE ENTRY_DATE
------------- ----------- -------------- ------------
9 5814 Nov 1 2008 Apr 20 2009
10 5814 Nov 10 2009 Nov 25 2009
11 5814 Nov 5 2009 Nov 26 2009
What I need is as follows...
For Nov 1 - Nov 4, salary should be processed as per employee_salary_masterId - 9 and
Nov 5 - Nov 30, salary should be processed as per employee_salary_masterId - 11.
SAL_MATSER_ID EMPLOYEE_ID EFFECTIVE_DATE ENTRY_DATE
------------- ----------- -------------- ------------
9 5814 Nov 1 2008 Apr 20 2009
11 5814 Nov 5 2009 Nov 26 2009
Please help me build this query.
Not quite sure if I understand you completely correct, but have a look at this example
DECLARE #employee_salary_master TABLE(
EMPLOYEE_SALARY_MASTER_ID INT,
EMPLOYEE_ID INT,
EFFECTIVE_DATE DATETIME,
ENTRY_DATE DATETIME
)
INSERT INTO #employee_salary_master SELECT 1,5814,'Jan 6 2006','Jan 12 2006'
INSERT INTO #employee_salary_master SELECT 2,5814,'Jan 10 2006','Jul 17 2006'
INSERT INTO #employee_salary_master SELECT 3,5814,'Jan 20 2006','Dec 22 2006'
INSERT INTO #employee_salary_master SELECT 4,5814,'May 10 2007','Jul 18 2007'
INSERT INTO #employee_salary_master SELECT 5,5814,'Nov 1 2007','Dec 18 2007'
INSERT INTO #employee_salary_master SELECT 6,5814,'Aug 1 2008','Aug 20 2008'
INSERT INTO #employee_salary_master SELECT 7,5814,'May 1 2008','Sep 2 2008'
INSERT INTO #employee_salary_master SELECT 8,5814,'Sep 1 2009','Sep 18 2008'
INSERT INTO #employee_salary_master SELECT 9,5814,'Nov 1 2008','Apr 20 2009'
INSERT INTO #employee_salary_master SELECT 10,5814,'Nov 10 2009','Nov 25 2009'
INSERT INTO #employee_salary_master SELECT 11,5814,'Nov 5 2009','Nov 26 2009'
DECLARE #monthfirstdate DATETIME,
#monthlastdate DATETIME
SELECT #monthfirstdate = '01 Nov 2009',
#monthlastdate = '30 Nov 2009'
SELECt *
FROM (
SELECT TOP 1
*
FROM #employee_salary_master esm
WHERE esm.EFFECTIVE_DATE BETWEEN #monthfirstdate and #monthlastdate
AND esm.EFFECTIVE_DATE < esm.ENTRY_DATE
ORDER BY esm.ENTRY_DATE DESC
) sub
UNION ALL
SELECT *
FROM (
SELECT TOP 1
*
FROM #employee_salary_master esm
WHERE esm.EFFECTIVE_DATE <= #monthfirstdate
AND esm.EFFECTIVE_DATE < esm.ENTRY_DATE
ORDER BY esm.EFFECTIVE_DATE DESC
) sub
ORDER BY EFFECTIVE_DATE
The rule for excluding nov 10 record is that we need to filter out those records for the month of November in which entry_date is greater but effective_date is smaller.
Let me explain you wrt data provided:
As a rule, the latest/last entry will take precedence over the previous entries in a particular month which implies that the entrty date of Nov 26 2009 would take precedence over the entry date of Nov 25 2009. Now since effective date of SAL_MATSER_ID - 10 is greater than that of SAL_MATSER_ID - 11, hence Nov 10 record would be nullified.
Had the data been like the below, all the 3 records would have been used for salary processing.
SAL_MATSER_ID - 9 for salary of Nov 1 - Nov 9
SAL_MATSER_ID - 10 for salary of Nov 10 - Nov 14
SAL_MATSER_ID - 11 for salary of Nov 15 - Nov 30
SAL_MATSER_ID EMPLOYEE_ID EFFECTIVE_DATE ENTRY_DATE
------------- ----------- -------------- ------------
9 5814 Nov 1 2008 Apr 20 2009
10 5814 Nov 10 2009 Nov 25 2009
11 5814 Nov 15 2009 Nov 26 2009
But since SAL_MATSER_ID - 11 is applicable from 5th Nov. onwards, the previous record is nullified. I hope this explains the situation.
Thanks for your support,
Sweta

Resources