use query results for another query sql - sql-server

I know that there are many topics discussing nested queries, however I am getting errors on my nested query due to the functions I am using.
Sample Data:
Sample TestDate Column:
2015-05-13 13:45:14.000
2015-05-15 07:33:13.000
2015-05-18 06:07:11.000
2015-05-19 02:58:13.000
2015-05-22 14:08:42.000
2015-05-26 11:01:29.000
2015-05-26 11:01:50.000
2015-05-27 07:19:32.000
2015-05-15 08:04:28.000
2015-05-15 10:32:23.000
2015-05-22 14:11:26.000
2015-05-27 07:16:57.000
2015-05-29 08:50:36.000
2015-05-15 10:38:23.000
2015-05-19 03:08:53.000
2015-05-27 13:41:47.000
2015-05-29 08:47:56.000
2015-05-15 07:50:04.000
2015-05-18 06:20:28.000
2015-05-19 06:32:24.000
2015-05-26 11:00:58.000
2015-05-22 14:12:15.000
2015-05-26 10:57:17.000
I am looking to query the last 7 DATES with data (may not be the last 7 days).
My query to return the last 7 Dates with data works well.
-- Set the return record count to the last 7 days
SET ROWCOUNT 7
--Get the Distinct Dates
SELECT DISTINCT(CONVERT(VARCHAR, CONVERT(DATETIME,[TestDate]),23)) AS DT
FROM [SERVER].[dbo].[TABLE]
--Get the last 60 days
WHERE [TestDate] BETWEEN (Getdate() - 60) AND Getdate()
--Start at the current date and go backwards.
ORDER BY DT DESC
-- reset the return record count to prevent issues with further queries.
SET ROWCOUNT 0
This provides the following result:
DT
2015-05-29
2015-05-27
2015-05-26
2015-05-22
2015-05-19
2015-05-18
2015-05-15
Now, I want to use those 7 entries to pull the data for those dates.
Usually I would do a
SELECT * WHERE [TestDate] >= '2015-05-29' AND [TestDate] <= '2015-05-30'
for example (cumbersome I know).
A) I get errors with the SET function in a nested query.
B) How to make the proper WHERE statement. One option is to use the first and last result (2015-05-29 and 2015-05-15) from the query
(WHERE [TestDate] >= 'FIRST_RESULT' AND [TestDate] <= 'LAST_RESULT')
EDIT:
So from the table I added above, I would want data from 2015-05-15 - 2015-05-29 (ie the results from the query), but not from the data on date 2015-05-13, since data from the 13 th is the 8 th day.

This would give you the last 7 dates with data without having to do what you've done in your sample code:
SELECT DISTINCT TOP 7
CAST([TestDate] AS DATE) DT
FROM YourTable
ORDER BY CAST([TestDate] AS DATE) DESC
I've cast them to DATE to get the date portion.
You can use this to JOIN on to, which will restrict the output to rows with a matching date:
SELECT *
FROM YourTable t1
INNER JOIN ( SELECT DISTINCT TOP 7
CAST(TestDate AS DATE) DT
FROM YourTable
ORDER BY CAST(TestDate AS DATE) DESC
) dts ON dts.DT = CAST(t1.TestDate AS DATE)

Related

Create a select statement that returns a record for each day after a given created date

I have a Dimension table containing machines.
Each machine has a date created value.
I would like to have a Select statement that generates for each day after a certain start date the available number of machines. A machine is available after the date created on wards
As I have read only access to the database I am not able to create a physical calendar table
I hope somebody can help me solving my issue
I assume this is what you want. Based on this sample table:
USE tempdb;
GO
CREATE TABLE dbo.Machines
(
MachineID int,
CreatedDate date
);
INSERT dbo.Machines VALUES(1,'20200104'),(2,'20200202'),(3,'20200214');
Then say you wanted the number of active machines starting on January 1st:
DECLARE #StartDate date = '20200101';
;WITH x AS
(
SELECT n = 0 UNION ALL SELECT n + 1 FROM x
WHERE n < DATEDIFF(DAY, #StartDate, GETDATE())
),
days(d) AS
(
SELECT DATEADD(DAY, x.n, #StartDate) FROM x
)
SELECT days.d, MachineCount = COUNT(m.MachineID)
FROM days
LEFT OUTER JOIN dbo.Machines AS m
ON days.d >= m.CreatedDate
GROUP BY days.d
ORDER BY days.d
OPTION (MAXRECURSION 0);
Results:
d MachineCount
---------- ------------
2020-01-01 0
2020-01-02 0
2020-01-03 0
2020-01-04 1
2020-01-05 1
...
2020-01-31 1
2020-02-01 1
2020-02-02 2
2020-02-03 2
...
2020-02-12 2
2020-02-13 2
2020-02-14 3
2020-02-15 3
Clean up:
DROP TABLE dbo.Machines;
(Yes, some people hiss at recursive CTEs. You can replace it with any number of set generation techniques, some I talk about here, here, and here.)

UPDATE SQL Query to update a table based on two dates

i would like to update my query table based on two dates, i tried the following code but it didn't work
UPDATE [Stock Report] INNER JOIN Report ON [Stock Report].ItemID = Report.ItemID SET [Stock Report].Amount = SUM(Report.Amount) WHERE [Date Product Was Made] BETWEEN #AA AND #BB
My two query tables are Report and Stock Report
Report Table
ItemID| Item |Date Product Was Made|Amount|ProductID|Product Name
10 Flour 11/17/2015 100 54 Saltbread
11 Bran Flakes 11/17/2015 100 54 Saltbread
10 Flour 11/17/2015 100 54 Saltbread
11 Bran Flakes 11/17/2015 100 54 Saltbread
What i would like to see in Stock Report Table
ItemID| Item | Start Date | End Date |Amount
10 Flour 11/16/2015 11/25/2015 200
11 Bran Flakes 11/16/2015 11/25/2015 200
The dates can be any two random dates but the table should generate a total based on the amount used in between the date ranges. Wht]at would be the SQL code to complete this process
As EuphoriaGrogi mentioned, you were pretty close.
SELECT ItemID, Item, #AA AS StartDate, #BB AS EndDate, SUM(Amount) AS TotalAmount
FROM (YourReportTableQueryWith#AAAnd#BBParametersHere) AS SubQuery
GROUP BY SubQuery.ItemID,SubQuery.Item
More on GROUP BY here: http://www.w3schools.com/sql/sql_groupby.asp
You tagged with mysql, sql-server and ms-access.
But answers will differ for each case.
Here SQLServer solution:
WITH SumAmount AS (
SELECT
ItemId
,SUM(Report.amount) as sum_amount
FROM
Report
GROUP BY
ItemId
)
UPDATE SR
SET
amount = SA.sum_amount
FROM
[Stock Report] SR
JOIN SumAmount SA ON SR.ItemID = SA.ItemID
WHERE
[Date Product Was Made] BETWEEN #AA AND #BB
Supposed MS Access query (I'm not proficient with MSACCESS, going by http://www.fmsinc.com/microsoftaccess/query/snytax/update-query.html):
UPDATE [Stock Report]
JOIN (
SELECT
ItemId
,SUM(Report.amount) as sum_amount
FROM
Report
GROUP BY
ItemId
) SA ON [Stock Report].ItemID = SA.ItemID
SET
[Stock Report].amount = SA.sum_amount
WHERE
[Date Product Was Made] BETWEEN #AA AND #BB

GROUP BY DAY, CUMULATIVE SUM

I have a table in MSSQL with the following structure:
PersonId
StartDate
EndDate
I need to be able to show the number of distinct people in the table within a date range or at a given date.
As an example i need to show on a daily basis the totals per day, e.g. if we have 2 entries on the 1st June, 3 on the 2nd June and 1 on the 3rd June the system should show the following result:
1st June: 2
2nd June: 5
3rd June: 6
If however e.g. on of the entries on the 2nd June also has an end date that is 2nd June then the 3rd June result would show just 5.
Would someone be able to assist with this.
Thanks
UPDATE
This is what i have so far which seems to work. Is there a better solution though as my solution only gets me employed figures. I also need unemployed on another column - unemployed would mean either no entry in the table or date not between and no other entry as employed.
CREATE TABLE #Temp(CountTotal int NOT NULL, CountDate datetime NOT NULL);
DECLARE #StartDT DATETIME
SET #StartDT = '2015-01-01 00:00:00'
WHILE #StartDT < '2015-08-31 00:00:00'
BEGIN
INSERT INTO #Temp(CountTotal, CountDate)
SELECT COUNT(DISTINCT PERSON.Id) AS CountTotal, #StartDT AS CountDate FROM PERSON
INNER JOIN DATA_INPUT_CHANGE_LOG ON PERSON.DataInputTypeId = DATA_INPUT_CHANGE_LOG.DataInputTypeId AND PERSON.Id = DATA_INPUT_CHANGE_LOG.DataItemId
LEFT OUTER JOIN PERSON_EMPLOYMENT ON PERSON.Id = PERSON_EMPLOYMENT.PersonId
WHERE PERSON.Id > 0 AND DATA_INPUT_CHANGE_LOG.Hidden = '0' AND DATA_INPUT_CHANGE_LOG.Approved = '1'
AND ((PERSON_EMPLOYMENT.StartDate <= DATEADD(MONTH,1,#StartDT) AND PERSON_EMPLOYMENT.EndDate IS NULL)
OR (#StartDT BETWEEN PERSON_EMPLOYMENT.StartDate AND PERSON_EMPLOYMENT.EndDate) AND PERSON_EMPLOYMENT.EndDate IS NOT NULL)
SET #StartDT = DATEADD(MONTH,1,#StartDT)
END
select * from #Temp
drop TABLE #Temp
You can use the following query. The cte part is to generate a set of serial dates between the start date and end date.
DECLARE #ViewStartDate DATETIME
DECLARE #ViewEndDate DATETIME
SET #ViewStartDate = '2015-01-01 00:00:00.000';
SET #ViewEndDate = '2015-02-25 00:00:00.000';
;WITH Dates([Date])
AS
(
SELECT #ViewStartDate
UNION ALL
SELECT DATEADD(DAY, 1,Date)
FROM Dates
WHERE DATEADD(DAY, 1,Date) <= #ViewEndDate
)
SELECT [Date], COUNT(*)
FROM Dates
LEFT JOIN PersonData ON Dates.Date >= PersonData.StartDate
AND Dates.Date <= PersonData.EndDate
GROUP By [Date]
Replace the PersonData with your table name
If startdate and enddate columns can be null, then you need to add
addditional conditions to the join
It assumes one person has only one record in the same date range
You could do this by creating data where every start date is a +1 event and end date is -1 and then calculate a running total on top of that.
For example if your data is something like this
PersonId StartDate EndDate
1 20150101 20150201
2 20150102 20150115
3 20150101
You first create a data set that looks like this:
EventDate ChangeValue
20150101 +2
20150102 +1
20150115 -1
20150201 -1
And if you use running total, you'll get this:
EventDate Total
2015-01-01 2
2015-01-02 3
2015-01-15 2
2015-02-01 1
You can get it with something like this:
select
p.eventdate,
sum(p.changevalue) over (order by p.eventdate asc) as total
from
(
select startdate as eventdate, sum(1) as changevalue from personnel group by startdate
union all
select enddate, sum(-1) from personnel where enddate is not null group by enddate
) p
order by p.eventdate asc
Having window function with sum() requires SQL Server 2012. If you're using older version, you can check other options for running totals.
My example in SQL Fiddle
If you have dates that don't have any events and you need to show those too, then the best option is probably to create a separate table of dates for the whole range you'll ever need, for example 1.1.2000 - 31.12.2099.
-- Edit --
To get count for a specific day, it's possible use the same logic, but just sum everything up to that day:
declare #eventdate date
set #eventdate = '20150117'
select
sum(p.changevalue)
from
(
select startdate as eventdate, 1 as changevalue from personnel
where startdate <= #eventdate
union all
select enddate, -1 from personnel
where enddate < #eventdate
) p
Hopefully this is ok, can't test since SQL Fiddle seems to be unavailable.

T sql group by month

I'm trying to group by according to month from datetime
I run below query
select cf.flow_name as 'Process', COUNT(c.case_ID) as 'Case', CONVERT(VARCHAR(10),c.xdate,104) as 'Date'
from cases c inner join case_flow cf on c.case_flow_ID=cf.CF_ID
where project_ID=1 and c.subject_ID=1
group by cf.flow_name,c.xdate
Columns data types as below
flow_name varchar(100)
case_ID int
xdate datetime
Result displays like below if i run above query
Process - Case - Date
Test 1 30.01.2015
Test 1 30.01.2015
analysis 1 19.03.2015
analysis 1 30.03.2015
analysis 1 13.04.2015
analysis 1 16.04.2015
Question:
I need to group by as below (group by according to month for x.date)
Correct Result should be as below
Process - Case - Date
Test 2 30.01.2015 (Because Test has 2 data from 01 month)
analysis 2 19.03.2015 (Because analysis has 2 data from 03 month)
analysis 2 13.04.2015 (Because analysis has 2 data from 04 month)
as above all result should group by month how can i do this according to my query ?
hope you understand my english thanks
SELECT cf_flow,
Count(*),
Min(xdate)
FROM cases c
INNER JOIN case_flow cf
ON c.case_flow_id = cf.cf_id
WHERE project_id = 1
AND c.subject_id = 1
GROUP BY cf_flow,
Dateadd(month, Datediff(month, 0, xdate), 0)

Calculate Time Difference Between Two Rows

I have a table that contains the following:
DataDate Value
2010-03-01 08:31:32.000 100
2010-03-01 08:31:40.000 110
2010-03-01 08:31:42.000 95
2010-03-01 08:31:45.000 101
. .
. .
. .
I need to multiply the value column by the difference in time between the current and previous rows and sum that for the entire day.
I currently have the data set up to come in every 10 seconds which makes for a simple conversion in the query:
SELECT Sum((Value/6) FROM History WHERE DataDate BETWEEN #startDate and #endDate
Where #startDate and #endDate are today's date at 00:00:00 and 11:59:59.
Before I set the data to be collected every 10 seconds it was collected whenever the Value changed. There aren't any duplicate entries in terms of time, the minimum time difference is 1 second.
How can I set up a query to get the elapsed time between rows for the case when I don't know the time interval between readings?
I am using SQL Server 2005.
WITH rows AS
(
SELECT *, ROW_NUMBER() OVER (ORDER BY DataDate) AS rn
FROM mytable
)
SELECT DATEDIFF(second, mc.DataDate, mp.DataDate)
FROM rows mc
JOIN rows mp
ON mc.rn = mp.rn - 1
In SQL Server 2012+:
SELECT DATEDIFF(second, pDataDate, dataDate)
FROM (
SELECT *,
LAG(dataDate) OVER (ORDER BY dataDate) pDataDate
FROM rows
) q
WHERE pDataDate IS NOT NULL
A little tweak on Quassnoi's query if you prefer not to use a Subselect would be:
SELECT
DATEDIFF(second, LAG(dataDate) OVER (ORDER BY dataDate), dataDate)
FROM rows
WHERE LAG(dataDate) OVER (ORDER BY dataDate) IS NOT NULL

Resources