How to calculate if date in database has expired within LINQ - sql-server

I have a requirement to find all records using EntityFramework via LINQ where the date stored in the database is almost expired. If the date in the database is almost 2 years old then it is expired (2 years - 90 days). We want users to be notified at 90 days prior to 2 years.
My users table has DateStamp column with the date. Thus the entity has a DateStamp property. I'm not sure how to construct the LINQ to determine if the date is 2 years - 90 days or not.
from u in Users
where u.DateStamp.....what's next?

You can use temp DateTime variable
DateTime temp = DateTime.Now.AddYears(-2).AddDays(90);
var users = (from u in Users where u.DateStamp <= temp select u);

Related

How to fetch only last 1 hour entries from a SQL Server or Oracle table?

I have a log table where I have a date column log_date value like 2021-03-02 07:51:41.000 in the format.
My requirement is that on click of a button I want to list out of the log entries from the last hour.
I searched SO and find out the below query which is for MySQL.
I need two separate T-SQL queries that should work on SQL Server and Oracle for my requirement since the common query is not possible.
What is the best way to fetch the last 1 hour records from the log table for SQL and Oracle (separate query)?
select count(*) as cnt
from log
where log_date >= DATE_SUB(NOW(), INTERVAL 1 HOUR);
Create a database view in each of your databases, that filter only teh last hour of the log table.
here an example for Oracle
create view log_last_hour as
select *
from log
where log_date >= sysdate - interval '1' hour;
Than you can use a single simple query that is database independent
Example
select count(*) from log_last_hour

Count by days, with all days

I need to count records by days, even if in the day were no records.
Count by days, sure, easy.
But how i can make it to print information, that 'in day 2018-01-10 was 0 records)
Should I use connect by level? Please, any help would be good. Can't use plsql, just oracle sql
First you generate every date that you want in an inline view. I chose every date for the current year because you didn't specify. Then you left outer join on date using whichever date field you have in that table. If you count on a non-null field from the source table then it will count 0 rows on days where there is no join.
select Dates.r, count(tablename.id)
from (select trunc(sysdate,'YYYY') + level - 1 R
from dual
connect by level <= trunc(add_months(sysdate,12),'YYYY') - trunc(sysdate,'YYYY')) Dates
left join tablename
on trunc(tablename.datefield) = Dates.r
group by Dates.r

Get total sum for each month in DAX

I have a tabular mode analysis server connected to a sql server database. I want to get the total x per month, and I have the total x per day. So for example, I have a table DailyEvent with the first 2 columns like this, and I want the column "MonthXCount":
TimeID XCount MonthXCount
20160429 3 11
20160430 8 11
20160501 4 4
So the total XCount for April is 11, so for every day in April I want 11. The total X count for may is 4 (so far).
What I have now is a MonthToDate total I think, calculated as:
=TOTALMTD(SUM('DailyEvent'[XCount]),'DailyEvent'[TimeID])
But I want to then have a column that puts the last value of the month in for every day of the month.
The end goal is to have a XCount by month graph in PowerBI, so I might not need to add the column here... I might be able to just tell PowerBi to graph the last day of the month, but I'm not sure how to do that and thought this would be easier.
SqlConnection sqlConnection1 = new SqlConnection("Your Connection String");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = "begin transaction t
update table dailyevent
set monthxcount = (select top(1) monthxcount
from dailyevent
where MONTH(timeID) = 4
order by monthxcount desc)
where MONTH(timeID) = 4
--commit only if the rows affected corresponds to the number of rows found for the month of april.
commit";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
// Data is accessible through the DataReader object here.
sqlConnection1.Close();
Do you have a Calendar Table in your model connected to your data table?
If yes, let's say the Calendar Table is called DimDate and that it contains a column called YearMonth, then the formula would be:
Month Sales := SUMX(
VALUES(DimDate[YearMonth]),
SUM(DailyEvent[XCount])
)
If you don't have a Calendar Table, then you can create a calculated column in your table called YearMonth with this formula:
=LEFT(DailyEvent[TimeID], 6)
Then calculate the sum of Month Sales with:
Month Sales := SUMX(
VALUES(DailyEvent[YearMonth]),
SUM(DailyEvent[XCount])
)
Hope this helps!
A note with respect to the formula you were using:
Time intelligence functions, such as TOTALMTD, require Calendar Tables. Therefore, be sure to add one to your data model before using them.
Edit:
Another solution could be to create a date column:
= DATE(
LEFT(DailyEvent[TimeID], 4),
MID(DailyEvent[TimeID], 5, 2),
1)
Then drop that column in the X-axis of the graph and the XCount column in the Y-axis.
You could use a measure calculation in Power BI, or in SSAS model, if there is a calendar table, make sure it is marked as date table otherwise the time logic will not work. I used the following query (DAX) it calculates the Month To Date
MtD :=CALCULATE(SUM('DailyEvent'[XCount]),DATESMTD('DateTabe'[calendarDate]))
If however there is no calendar or you are working with the be-spoke calendar, this may help
Running Totals Whitout a Traditional Calendar Table

SQL Server Stored Procedure get nearest available date to parameter

I have a table of database size information. The data is collected daily. However, some days are missed due to various reasons. Additionally we have databases which come and go over or the size does not get recorded for several databases for a day or two. This all leads to very inconsistent data collection regarding dates. I want to construct a SQL procedure which will generate a percentage of change between any two dates (1 week, monthly, quarterly, etc.) for ALL databases The problem is what to do if a chosen date is missing (no rows for that date or no row for one or more databases for that date). What I want to be able to do is get the nearest available date for each database for the two dates (begin and end).
For instance, if database Mydb has these recording dates:
2015-05-03
2015-05-04
2015-05-05
2015-05-08
2015-05-09
2015-05-10
2015-05-11
2015-05-12
2015-05-14
and I want to compare 2015-05-06 with 2015-05-14
The 2015-05-07 date is missing so I would want to use the next available date which is 2015-05-08. Keep in mind, MyOtherDB may only be missing the 2015-05-06 date but have available the 2015-05-07 date. So, for MyOtherDb I would be using 2015-05-07 for my comparison.
Is there a way to proceduralize this with SQL WITHOUT using a CURSOR?
You're thinking too much into this, simple do a "BETWEEN" function in your where clause that takes the two parameters.
In your example, if you perform the query:
SELECT * FROM DATABASE_AUDIT WHERE DATE BETWEEN param1 /*2015-05-06*/ and param2 /*2015-05-14*/
It will give you the desired results.
select (b.dbsize - a.dbsize ) / a.dbsize *100 dbSizecChangePercent from
( select top 1 * from dbAudit where auditDate = (select min(auditDate) from dbAudit where auditDate between '01/01/2015' and '01/07/2015')) a
cross join
(select top 1 * from dbAudit where auditDate = (select max(auditDate) from dbAudit where auditDate between '01/01/2015' and '01/07/2015')) b
The top 1 can be replaced by a group by. This was assuming only 1 db aduit per day

Sql Server Selecting 1 single datapoint every hour or every day from a table

Hi I have several tables in sql server that record data every 30 seconds. obviously after a while that gets a bit bulky, what I'd like to do is select 1 datapoint an hour over the past 24 hours and put that into a seperate tables for fast quesries, so I was thinking once every hour over a 24 hour period, 2 times a day over a week long period, and once a day over a month long period. I have datetime recorded on every data point we have.
I'd like something like this for the once an hour over 24 hours
Select * from MiscTBL Where Date >= (( Currentdatetime - 24 hh )) group by hh
thank you for any advice
Also I'm using sql server management studio it would be great if this were an automatically updating process so I had seperate tables I could use for faster queries of data over shorter pre quantified time periods
Something like this would return 1 sample per hour:
select *
from ActivityLog
where id in
(select max(id) maxID
from ActivityLog
where activityDateTime between #startDateTime and #endDateTime
group by DATEPART(hour, activityDateTime))
I would use this concept to build a stored proc that moved the data around and then I would schedule it to run as often as needed using a SQL Agent job.

Resources