Selecting records from the past three months - sql

I have 2 tables from which i need to run a query to display number of views a user had in the last 3 months from now.
So far I have come up with: all the field types are correct.
SELECT dbo_LU_USER.USERNAME
, Count(*) AS No_of_Sessions
FROM dbo_SDB_SESSION
INNER JOIN dbo_LU_USER
ON dbo_SDB_SESSION.FK_USERID = dbo_LU_USER.PK_USERID
WHERE (((DateDiff("m",[dbo_SDB_SESSION].[SESSIONSTART],Now()))=0
Or (DateDiff("m",[dbo_SDB_SESSION].[SESSIONSTART],Now()))=1
Or (DateDiff("m",[dbo_SDB_SESSION].[SESSIONSTART],Now()))=2))
GROUP BY dbo_LU_USER.USERNAME;
Basically, the code above display a list of all records within the past 3 months; however, it starts from the 1st day of the month and ends on the current date, but I need it to start 3 months prior to today's date.
Also to let you know this is SQL View in MS Access 2007 code.
Thanks in advance

Depending on how "strictly" you define your 3 months rule, you could make things a lot easier and probably efficient, by trying this:
SELECT dbo_LU_USER.USERNAME, Count(*) AS No_of_Sessions
FROM dbo_SDB_SESSION
INNER JOIN dbo_LU_USER
ON dbo_SDB_SESSION.FK_USERID = dbo_LU_USER.PK_USERID
WHERE [dbo_SDB_SESSION].[SESSIONSTART] between now() and DateAdd("d",-90,now())
GROUP BY dbo_LU_USER.USERNAME;
(Please understand that my MS SQL is a bit rusty, and can't test this at the moment: the idea is to make the query scan all record whose date is between "TODAY" and "TODAY-90 days").

Related

Records between 2 dates Oracle SQL

I am looking to filter out records between 2 dates. Here is a list of start and end dates. I need identify records that fall under the respective periods.
I am able to identify the records that fall in the first and last period i.e. first (9/07/2020 - 22/07/2020) and last (10/11/2020 - 23/12/2020) by using MIN and MAX. I am not able to find records that fall in between i.e. 2-11?
I have another table that shows a date when the records were updated. For instance,
I need to identify the records that falls under what periods. For instance,
Any kind of help would be appreciated!
Thanks
You need to do a join on your two tables. You don't give your table names, so this is a bit of guesswork, but try something like this:
select *
from period_table p
inner join record_table r on r.changed_date between p.startdate and p.enddate

SQL sum amount that lies between two dates

I have the following table in SQL:
Start - End - Amount **per day**
06.07.2020 10.07.2020 10
08.07.2020 08.07.2020 5
08.07.2020 15.07.2020 20
02.07.2020 06.07.2020 3
Now I want to filter this table by the calendar week. Let's say "where [calendar week] = cw28". cw28 is from the 06th of july to the 12th of july.
With that I'd like to have the sum of the amount of the days that lie between those two dates. One single number.
I'm using MS SQL Server (SQL Express).
I can't figure out how to distinguish (and break down) if one day lays between the two date values or not. And if yes how much I need to sum up.
I tried to make a picture in excel to create a logic from this:
"Logic" in Excel
Can anyone help me with this? :)
Thx and Best!,
Max
Not sure about your exact requirement. But below is the query to get the sum of values between two dates.
select sum(amount_of_days) from table where date_column between '06-JUL-2020' and '07-JUL-2010';
Change the column name and table name according to your requirement

Same dates from and to not showing data

the following is the sql being executed in my Crystal report.
There seems to be an issue with the same date request. Sometimes it shows data, other times not. We have data every day, we are a mass market company. Is there anything i can do for the sql to do select when from and to dates are the same?
SELECT "OEHIS1"."ODORD#", "OEHIS1"."ODORDT", "OEHIS1"."ODNTU$", "OEHIS1"."ODSHP#", "ICPRT1"."IARC11", "OEHIS1"."ODORDD", "ICPRT1"."IARCC4", "OEHIS1"."ODQTY#", "OEHIS1"."ODRQSD", "MFHHMH"."MHAWGT", "OEHIS1"."ODPRT#", "OEHIS1"."ODPRLC"
FROM ("S10M10"."ASTCCDTA"."EODDETAILS" "OEHIS1" INNER JOIN "S10M10"."ASTDTA"."ICPRT1" "ICPRT1" ON "OEHIS1"."ODPRT#"="ICPRT1"."IAPRT#") INNER JOIN "S10M10"."DLIB"."MFHHMH" "MFHHMH" ON "OEHIS1"."ODORD#"="MFHHMH"."MHORDP"
WHERE "OEHIS1"."ODPRT#" NOT LIKE 'FR%' AND "ICPRT1"."IARCC4"='FIN' AND "OEHIS1"."ODORDD"=20141027 AND NOT ("ICPRT1"."IARC11"='' OR "ICPRT1"."IARC11"='DRS') AND ("OEHIS1"."ODORDT"='CSA' OR "OEHIS1"."ODORDT"='CUS' OR "OEHIS1"."ODORDT"='INT' OR "OEHIS1"."ODORDT"='N4H' OR "OEHIS1"."ODORDT"='NFM' OR "OEHIS1"."ODORDT"='RTR') AND NOT ("OEHIS1"."ODPRLC" LIKE 'CMY%' OR "OEHIS1"."ODPRLC" LIKE 'DSC%' OR "OEHIS1"."ODPRLC" LIKE 'LGC%' OR "OEHIS1"."ODPRLC" LIKE 'X%')
ORDER BY "ICPRT1"."IARC11"
Migrated my comment to an answer, since that seemed to work for you.
I have very little CR experience, but with SQL you usually want to select between the day you want and the day after if you want results for today. That's because today, for example, is 10/27/2014, with no time. This defaults to midnight. If the date is the same on both sides, you'll only get results that happened at exactly midnight. Your query should be between 10/27/2014 and 10/28/2014 (midnight this morning to midnight tomorrow).

Matrix to show all months of the year

I have a Web Service that I am getting data from (Not mine and I can't change it)
The data is in the following format
<DealMetrics>
<DealId>1</DealId>
<DealName>ABC</DealName>
<FundAbbreviation>ABC</FundAbbreviation>
<NavYear>2012</NavYear>
<NavMonth>January</NavMonth>
<Nav>123</Nav>
.
.
.
</DealMetrics>
I have a matrix that displays this performance data and works fine - I have a row group on the year and a column group on the month. The problem occurs if a deal has only been running for a short time - I want to display all months regardless of whether we have any data - So for example if a deal started in September and we're in December I'd want the column headings to display for Jan - Aug as well as the data that is returned in the web service.
Any ideas?
Regards
Andy
Might not be the most elegant way of doing it (I'm a relative newbie to SQL!) but I would create a table which is effectively a calendar of all the months within the period you are interested in (using a recursive CTE) and then just join the results of the query from the web service onto that?
Assuming your metrics end up in a SQL Server table with the following columns:
-- Metrics table:
DealId
DealName
FullAbbreviation
NavYear
NavMonth
Nav
Create a calendar table to hold all years and months you could possibly be interested in. For instructions on how to create a calendar table, check out this post, for example: How to create a Calender table for 100 years in Sql
Then, when you have your calendar table, use it in an outer join with your metrics table, so that you get all your years and months from the calendar table, and the metric data (if any). The query in your dataset could for example look like this:
SELECT DealId,
DealName,
FullAbbreviation,
ISNULL(NavYear, Months.Year) AS NavYear,
ISNULL(NavMonth, Months.Month) AS NavMonth,
Nav
FROM
(SELECT DISTINCT Year, Month, MonthNumber FROM Calendar) AS Months
LEFT JOIN Metrics ON Months.Year = Metrics.NavYear AND Months.Month = Metrics.NavMonth
ORDER BY NavYear, NavMonth

GROUP BY with date range

I have a table with 4 columns, id, Stream which is text, Duration (int), and Timestamp (datetime). There is a row inserted for every time someone plays a specific audio stream on my website. Stream is the name, and Duration is the time in seconds that they are listening. I am currently using the following query to figure up total listen hours for each week in a year:
SELECT YEARWEEK(`Timestamp`), (SUM(`Duration`)/60/60) FROM logs_main
WHERE `Stream`="asdf" GROUP BY YEARWEEK(`Timestamp`);
This does what I expect... presenting a total of listen time for each week in the year that there is data.
However, I would like to build a query where I have a result row for weeks that there may not be any data. For example, if the 26th week of 2006 has no rows that fall within that week, then I would like the SUM result to be 0.
Is it possible to do this? Maybe via a JOIN over a date range somehow?
The tried an true old school solution is to set up another table with a bunch of date ranges that you can outer join with for the grouping (as in the other table would have all of the weeks in it with a begin / end date).
In this case, you could just get by with a table full of the values from YEARWEEK:
201100
201101
201102
201103
201104
And here is a sketch of a sql statement:
SELECT year_weeks.yearweek , (SUM(`Duration`)/60/60)
FROM year_weeks LEFT OUTER JOIN logs_main
ON year_weeks.yearweek = logs_main.YEARWEEK(`Timestamp`)
WHERE `Stream`="asdf" GROUP BY year_weeks.yearweek;
Here is a suggestion. might not be exactly what you are looking for.
But say you had a simple table with one column [year_week] that contained the values of 1, 2, 3, 4... 52
You could then theoretically:
SELECT
A.year_week,
(SELECT SUM('Duration')/60/00) FROM logs_main WHERE
stream = 'asdf' AND YEARWEEK('TimeStamp') = A.year_week GROUP BY YEARWEEK('TimeStamp'))
FROM
tblYearWeeks A
this obviously needs some tweaking... i've done several similar queries in other projects and this works well enough depending on the situation.
If your looking for a one table/sql based solution then that is deffinately something I would be interested in as well!