Find Gaps in a single date column SQL Server - sql

Good Day everyone,
I need your help.
I am trying to detect gaps in a single column of the type Date or DateTime in SQL Server.
Say we have a list of schools and each school has many records and there is a field of uploadDate.
So something like that:
My outcome would be something like that:
Thank you all.

You can use lead():
select name, dateadd(day, 1, upload_date), dateadd(day, -1, next_upload_date)
from (select t.*,
lead(upload_date) over (partition by name order by upload_date) as next_upload_date
from t
) t
where next_upload_date <> dateadd(day, 1, upload_date);

Related

How to increase the duration logic in SQL SP

I have a stored procedure which deletes the records from DB based on following logic.
Select Id into #deleterecords from pricetable where
((Convert(date, modifiedon) <> convert(date,gatedate())
I would like to add one more day in Gatedate()
I’m trying in this
Select Id into #deleterecords from pricetable where
((Convert(date, modifiedon) < > convert(date,gatedate()+1)
It’s not working.
How can I add one more day?
What do you mean by "It’s not working."? Are you getting some error message?
Did you mean to write GETDATE() (the built-in function that returns the current timestamp), or you indeed have a gatedate() function in your database?
To add a day to a datetime value in SQL Server use the function DATEADD.
select Id
into #deleterecords
from pricetable
where
convert(date, modifiedon) <> convert(date, DATEADD(day, 1, gatedate()))
;

SQL query involving count, group by and substring

I would like to group rows of this table according to dates which form the start of SessionID and for each day, I would like to count how many rows there are for each set of ReqPhone values. Each set of ReqPhone values will be defined by the first four digits of ReqPhone. In other words, I would like to know how many rows there are for ReqPhone starting with 0925, 0927 and 0940, how many rows there are for ReqPhone starting with 0979, 0969 and 0955, etc etc.
I have been trying all kinds of group by and count but still haven't arrived at the right query.
Can anybody enlighten me?
Update:
In my country, the government assigns telecoms phone numbers starting with certain digits. Therefore, if you know the starting digits, you know which telecom someone is using. I am trying to count how many messages are sent each day using each telecoms.
SELECT SUBSTRING(ReqPhone, 1, 4),
DATEADD(DAY,0, DATEDIFF(DAY, 0, SessionID)) AS dayCreated,
COUNT(*) AS tally
FROM yourTable
GROUP BY SUBSTRING(ReqPhone, 1, 4),
DATEADD(DAY, 0, DATEDIFF(DAY, 0, SessionID))
SELECT LEFT(ReqPhone, 4),
DATEADD(DAY,0, DATEDIFF(DAY, 0, SessionID)) AS dayCreated,
COUNT(*) AS tally
FROM yourTable
GROUP BY LEFT(ReqPhone,4),
DATEADD(DAY, 0, DATEDIFF(DAY, 0, SessionID))
This will help you to calculate the count of rows group by the ReqPhone type. This query is working successfully in Oracle DB.
SELECT COUNT(SESSIONID), REQP
FROM (SELECT SESSIONID,SUBSTR(REQPHONE,1,4) AS REQP FROM SCHEMA_NAME.TABLE_NAME)
GROUP BY REQP
Note: Please use the column which is unique in the COUNT expression.

How can I group by day, and still return a datetime?

I want to track the users in my db, when they was created to show it in a awesome chart. Each user has a column "Created" that is the DateTime when they was created. Right down to the time that day.
However, for my chart I dont really care about the time, just the day, month and year. Is there a way I can return a datetime and count when I use datepart as the following:
SELECT datepart(year,Created), datepart(month,Created), datepart(day,Created), COUNT(*) AS COUNT
FROM [dbms].[User]
GROUP BY datepart(year,Created), datepart(month,Created), datepart(day,Created)
This returns three columns for year, month and day. Is there any way I could make it sexy and make it return DateTime (in YYYY/MM/DD format) and the cound?
If you're using SQL Server 2008 or later, you can take advantage of the date data type.
SELECT cast(Created as date), COUNT(*) AS COUNT
FROM [dbms].[User]
GROUP BY cast(Created as date)
If you're using SQL Server 2005 or earlier:
SELECT dateadd(day,datediff(day,0,Created), 0), COUNT(*) AS COUNT
FROM [dbms].[User]
GROUP BY dateadd(day,datediff(day,0,Created), 0)
You can try the following:
SELECT dateadd(day, datediff(day, 0, Created), 0) as date, COUNT(*) AS COUNT
FROM [dbms].[User]
GROUP BY dateadd(day, datediff(day, 0, Created), 0)
This will group you users by the creation date without time and will works on each versions of SQL Server. Among this, the Dateadd operation is more faster that casting...

How do I add the values of a column together dependant on another column

It's quite a hard one to explain but probably (hopefully) an easy one to solve so I'll just explain what it is I'm trying to achieve.
I have a table where multiple logs can be entered for a day each as a seperate row, I then have a decimal as another column, I'm trying to create a summary for each day which would be something like
01/01/1900 | | 5.5
When there's one entry for the 01/01/1900 with 2.5, one with 3 in the main table so adding the values together for the day?
My only issue is adding the dates together if the dates the same, I was thinking something like
Select distinct date and joining it with a table that gets the sum of the decimal column where date is... and that's where im not too sure?
Any help would be great! thanks
If your table is named logs with data like
log_date | value
1900-01-01 | 2.5
1900-01-01 | 3
then your query is
SELECT sum(value) FROM logs GROUP BY log_date
What you're looking for is probably a GROUP BY clause.
SELECT [ yourdatecol, ] sum(yourdecimalcol) FROM yourtable
[ WHERE yourdatecol = .. ]
GROUP BY [ get_ymd_from_date(yourdatecol) | yourdatecol ] ;
With such syntax you'll get sum of row sets, selected by the same datecol value. You may also want to approximate date ( e.g. taking only Y/M/D part from it ), if date contains H/M/ss and what you want is per-day sums. Optional parts I enclosed in square brackets.
SELECT log_date,sum(value) FROM logs GROUP BY log_date
CREATE VIEW Summary
AS
SELECT
DateValue,
SUM(DecimalValue) DayTotal
FROM
EventTable
GROUP BY
DateValue;
Then
SELECT
*
FROM
Summary
WHERE
DateValue = '1900-01-01'
Try this :
SELECT CONVERT(VARCHAR, DateColumn, 103) AS OutputDate, SUM(ValueColumn) AS TotalValue
FROM YourTable
GROUP BY CONVERT(VARCHAR, DateColumn, 103)
I'm presuming a DateTime is used, lets call it logdate. I'm also presuming the other one is a decimal, lets call it logdecimal.
Using SQL server 2008 you can do (the is a type called date which is without the time-part):
SELECT
CAST(logdate as date) as TheDay,
SUM(logdecimal) as TheSum
FROM logTable
GROUP BY CAST(logdatetime as date)
Using a SQL server without the type date, maybe something like:
SELECT
CONVERT(varchar(10), logdate, 101) as TheDay,
SUM(logdecimal) as TheSum
FROM logTable
GROUP BY CONVERT(varchar(10), logdate , 101)
Regards, Olle
Edit: This one will work if it is a DateTime (including time part) you want to group as a date (not including time part). Looks like this was not the case in this question.

SQL How to convert date DD-MM-YYYY to MM-YYYY and retrieve most recent records?

Hi I have to retrieve from my table most recent records that match a given MM-YYYY, but the date field in the table is DD-MM-YYYY, how do I get this done?
Thank you very much
Best Regards
Ignacio.
How many of the most recent records do you need?
Could you not query for all the dates in the relevant month, order by the dates, and then only select the results you need from the top of the list.
For example:
SELECT TOP(1) *
FROM your_table
WHERE date_time_field >= '20120101'
AND date_time_field < '20120201'
ORDER BY date_time_field DESC
This would select the most recent record from January of this year.
Change the number inside the TOP() statement to change the number of results returned, or leave it off altogether and take comfort in the fact that your results are ordered.
SELECT * FROM `your`.`schemaTableNames` WHERE your_coulumn_name LIKE "%-MM-YYYY";
should give you the matching records, as you wrote that you want to retrieve.
Have you tried using DateDiff(month, date1, date2) == 0 in your where clause?
This assumes that you can convert both values to DATETIME. If you only have the year and the month, every month has day 01.
to convert a date to desire format you can use style to retrive the records date formats
The following works:
right(select convert(varchar, <date field>, 110), 7)
The full query would look someting like this:
select *
from table
where right(select convert(varchar, <date field>, 110), 7) = 'MM-YYYY'