I have two columns of timestamps in a table and I want to get the average of their difference. An example could this:
| start_date | end_date |
---------------------------------------------
| 2022-01-01 12:00:00 | 2022-01-01 13:00:00 |
| 2022-01-02 10:00:00 | 2022-01-02 12:00:00 |
| ... | ... |
|___________________________________________
I need the average to be expressed in seconds and I know that in postgresql you can do it like this:
select
exctract(epoch from avg(end_date - start_date)) as average
from
tableA
but in sqlServer you do it this way:
select
DATEDIFF(second, start_date, end_date) as average
from
tableA
I need to make a query that does this average but that uses ANSI sql, so no matter which db i encounter, i always get the same result.
My complete query looks like this:
select
name, description, .. as average
from
tableA, tableB, tableC
where
.... /* join conditions etc */
group by
name, description
Is there a way to do this? I'm not an expert but if functions could be useful in this scenario that is fine. I didn't come up a solution though.
The most imprtant DBs I work with are postgresql, oracle, mysql, sqlserver.
Related
I've seen a few variations of writing dates in SQL Server as it doesn't support the more standard literal format of:
DATE '2014-01-01'
Is there a suggested way to write date-literals (or the closest thing to it) in SQL Server? Currently what I do is:
CAST('2014-01-01' AS date)
Whenever I want to use a date. Is this the most common?
SQL Server supports some date formats, but you can use '20220101'
CREATE TABLE t1([date] date)
INSERT INTO t1 values ('20220101')
SELECT * FROM t1
| date |
| :--------- |
| 2022-01-01 |
db<>fiddle here
You are misunderstanding SQL for TSQL.
In your SELECT date, '20220101' FROM t1the second is a string for SQL.
But as you see in the query below, TSQL will converts the text into a date automatically when comparing for example
SELECT CASE WHEN CAST('2014-01-01' AS date) > '20220101' THEN 'TRUE' ELSE 'FALSE' END
| (No column name) |
| :--------------- |
| FaLSE |
db<>fiddle here
I'm asking for your kindly explanation on this.
I have a Calendar table, where each day is having a row. Also I have a table with backup results, where the date and time of backup start is stored.
My goal is to have this result:
date of month | serverid | datetime of backup | result | note (not in table, for info only)
2022-02-02 | 11 | 2022-02-02 19:00 | OK | backup was successful
2022-02-03 | NULL | NULL | NULL | backup was not even start
2022-02-04 | 11 | 2022-02-04 19:00 | FAILED | backup started but error occured
I tried LEFT OUTER JOIN and OUTER APPLY.
LEFT OUTER JOIN is not returning the null lines where backup is not started
OUTER APPLY is working much better, but when I filter results by Year, Month (from calendar table) and serverid, NULL lines are gone also.
So my goal is to select ALL lines from calendar table in the specified month and year and assign the results to them by the backup start datetime column to see the days where the backup was not started also.
Can you please point me at right way?
Best Regards, Jan
Example of queries:
SELECT [SqlDt], [Year], [Month], A.*
FROM [portal].[dbo].[Calendar] C OUTER APPLY
(SELECT *
FROM [DS-Backup] D
WHERE [C].[SqlDt] = CAST(D .VersionDate AS Date)) A
SELECT dbo.Calendar.SqlDt, dbo.Calendar.Year, dbo.Calendar.Month, dbo.[DS-Backup].EID, dbo.[DS-Backup].VersionDate, dbo.[DS-Backup].VersionStatus
FROM dbo.Calendar LEFT OUTER JOIN
dbo.[DS-Backup] ON dbo.Calendar.SqlDt = CAST(dbo.[DS-Backup].VersionDate AS Date)
Thank you all for useful commnets, I was not filter the table with backup results before join.
Now it is working the way I want:
SELECT [SqlDt],[Year],[Month],[Backups].*
FROM [portal].[dbo].[Calendar]
LEFT JOIN ( SELECT * FROM [portal].[dbo].[DS-WindowsServerBackup] WHERE EID=11) as Backups
ON Calendar.SqlDt = CAST([Backups].[VersionDate] as Date)
I need to retrieve a set of rows based on a filtering criteria on Timestamp, which is - Timestamps with Time > 06:OO AM
However, I also need the immediate previous record less than 06:00 AM to calculate event duration's correctly
How can I retrieve the rows having Time > 6:00 AM AND the last row which is less than 6:00 AM?
Sample: I have these rows in the database and i have to calculate Event Duration's. If I just filter on Timestamp > 6:00 AM, the second also gets filtered out which i need for further calculations
Actual:
Event1 | Resource1 | 2019-05-26 04:38:16.1156432
Event2 | Resource1 | 2019-05-26 05:51:23.2356984
Event3 | Resource1 | 2019-05-26 06:01:32.1033333
Event4 | Resource1 | 2019-05-26 06:03:12.3245614
Applying the 'greater than 6:00AM' AND 'Previous row < 06:00AM' criteria, the result should look like:
1. Event2 | Resource1 | 2019-05-26 05:51:23.2356984
2. Event3 | Resource1 | 2019-05-26 06:01:32.1033333
3. Event4 | Resource1 | 2019-05-26 06:03:12.3245614
Considering we have very little to go on here, the best I can offer is Pseudo-SQL.
Anyway, seems like what you want is a CTE and LEAD:
WITH CTE AS(
SELECT {Your Columns},
LEAD({Your Date & Time Column}) OVER (/*PARTITION BY {Some Column(s)}*/ ORDER BY {Your Date & Time Column} AS NextTime --Uncomment/Remove PARTITION BY Clause as needed
FROM {Your TABLE} YT)
SELECT {Your Columns}
FROM CTE
WHERE NextTime >= '2019-05-26T06:00:00';
You'll need to replace the appropriate parts in the Braces ({}).
I am new to SQL Server world. I have a table as below:
alert_id | create_date | Status
---------+-------------+---------
1231 | 4/15/2017 | Open
1232 | 4/15/2017 | Open
1234 | 4/15/2017 | Closed
1235 | 4/16/2017 | Open
All of these alerts should be closed in 30 days. I need to get a forecast report which shows how many alerts are open for past 30 days.
I would like to write a select query whose output would be 2 columns. First would be Date and 2nd would be count. The date column should display all the dates for next 30 days and Count column should display the number of records which are due to expire on that day. Something like below would work. Please assist.
date | Count
----------+---------
5/15/2017 | 2
5/16/2017 | 3
5/17/2017 | 0
5/18/2017 | 0
.
.
.
6/14/2017 | 0
This is a job for GROUP BY and date arithmetic. In MySQL:
SELECT DATE(create_date) + INTERVAL 30 DAY expire_date, COUNT(*) num
FROM tbl
WHERE status = 'Open'
GROUP BY DATE(create_date)
DATE(create_date) + INTERVAL 30 DAY gets you the create date values with thirty days added.
GROUP BY(create_date) groups your data by values of your create date, truncated to midnight.
And, COUNT(*) goes with GROUP BY to tell you how many records in each group.
Edit In recent versions of SQL Server (MS)
SELECT DATEADD(day, 30, CAST(create_date AS DATE)) expire_date, COUNT(*) num
FROM tbl
WHERE status = 'Open'
GROUP BY CAST(create_date AS DATE)
Notice, please, that date arithmetic varies between make and model of SQL server software. That's why you get hassled by Stack Overflow users in comments when you use more than one tag like [oracle] [mysql] [sql-server] on your questions.
Cool, huh? You should read up on aggregate queries, sometimes called summary queries.
You're not going to get the missing dates with zeros by them. That's quite a bit harder to do with SQL.
My table:
Items | Price | UpdateAt
1 | 2000 | 02/02/2015
2 | 4000 | 06/04/2015
3 | 2150 | 07/05/2015
4 | 1800 | 07/05/2015
5 | 5540 | 08/16/2015
4 | 1700 | 12/24/2015
5 | 5200 | 12/26/2015
2 | 3900 | 01/01/2016
4 | 2000 | 06/14/2016
As you can see, this is a table that keeps items' price as well as their old price before the last update.
Now I need to find the rows which :
UpdateAt is more than 1 year ago from now
Must have updated price at least once ever since
Aren't the most up-to-date price
So with those conditions, the result from the above table should be :
Items | Price | UpdateAt
2 | 4000 | 06/04/2015
4 | 1800 | 07/05/2015
I can achieve what I need with this
Declare #LastUpdate date set #LastUpdate = DATEADD(YEAER, -1, GETDATE())
select Items, UpdateAt from ITEM_PRICE where Items in (
select Items from (
select Items, count(Items) as C from ITEM_PRICE group by Items) T
where T.C > 1)
and UpdateAt < #LastUpdate
But since I am still a newbie in sqlserver, and this need to be done in vb.net, passing along that query with lots of select in it seems sloppy and hard to maintain.
So, I would like to ask if anyone can give me a simpler solution ?
Sorry, i edited my question as I need one more condition to be met after trying #Tim Biegeleisen's answer, which is indeed the correct one for the question before edit. And I can't figure this out anymore.
Why I need all those condition, it's because I'm having to clean up the table: Clearing off the data that's older than 1 year, while still keeping the most up-to-date item price.
In my answer below, I use a subquery to identify all items which appear in the table during the last year. This is the requirement of having an updated price "at least once ever since." In the outer query, I restrict to only records which are older than one year from now, which is the other part of the requirement. An INNER JOIN is used, because we want to filter off records which do not meet both criteria.
SELECT t1.Items, t1.Price, t1.UpdateAt
FROM ITEM_PRICE t1
INNER JOIN
(
SELECT DISTINCT Items
FROM ITEM_PRICE
WHERE UpdateAt > DATEADD(year, -1, GETDATE())
) t2
ON t1.Items = t2.Items
WHERE t1.UpdateAt <= DATEADD(year, -1, GETDATE())
Once again, SQL Fiddle is having problems simulating SQL Server. But I went ahead and created a Fiddle in MySQL, which looks nearly identical to my SQL Server answer. You can verify that the logic and output are correct.
SQLFiddle