joining select statements? - sql

I would like to do a inner join in my query but I don´t know how to summarize my two select statements into one query.
This is the first query:
select
Machine
, EventDefinition
, Duration
, sum(Duration) over (partition by 1) As Total
, Duration/sum(Duration) over (partition by 1)*100 AS Distribution
,case when EventCategory < 0.05 Then 'NOT INCL' ELSE 'OK' END AS Under3Min
from (
Select
SystemName AS Machine
, EventDefinition
, EventDate
, EventStartDateTime
, IsNull(EventEndDateTime, GETDATE()) as EventEndDateTime
, Sum(cast(EventEndDateTime - EventStartDateTime as float))*24 as Duration
,Sum(case when CustomEvent = 'without Stop' then cast(EventEndDateTime - EventStartDateTime as float)*24 else 0 end) as EventCategory
FROM tDataCategory
WHERE EventDate >= #StartDateTime
AND EventDate <= #EndDateTime
AND SystemName = '201'
Group BY SystemName, eventdefinition, eventstartdatetime, eventenddatetime, EventDefinition, EventDate, CustomEvent
) as t
WHERE CustomEvent <> 'without Stop'
OR (CustomEvent = 'without Stop' AND t.EventCategory >=0.05)
group by EventDefinition
, Duration
,Machine
,EventCategory
output:
and my second query:
SELECT DataValue = case when Prod = 0 then 0 else ISNULL(100.0 / Prod * Scrap, 0) end,
Value = GoodUnits/TheoreticalUnits *100,
FROM (
Select intervaldate as DateValue, intervalDateWeek as Datum, tsystem.Name as Name, ProductName as Product, teamname as Team,
SUM(case when IssueName in ('A1', 'A2') then calculationUnitsInitial else 0 end) as Scrap,
Sum(case when IssueName = 'Prod' then calculationUnitsInitial else 0 end) as Prod,
SUM(GoodUnits)
As GoodUnits,
SUM(TheoreticalUnits) As TheoreticalUnits,
from tCount inner join tsystem ON tCount.systemid = tsystem.id
where IntervalDate >= dateadd(wk, datediff(wk, 1, getdate()), 0)
and IntervalDate <= dateadd(wk, datediff(wk, 0, getdate()), 0)
AND ((DATEPART(dw, IntervalDate) + ##DATEFIRST) % 7) NOT IN (0,1)
and tsystem.Name = '201'
group by intervaldate, tsystem.Name, intervaldateweek, ProductName, teamname
) as s
output:
I tried it to add in my query two select statements. But if I do this the output is wrong. I really don´t know how I should join this two queries.
I would like to do then this calculation: Distribution * (1 - Value)
Distribution from the first query and Value from the second query

I assume the first and second result set has to be joined based on A.Machine=B.Name
Try like this,
SELECT A.Distribution * (1 - B.Value)
FROM (
SELECT Machine
,EventDefinition
,Duration
,sum(Duration) OVER (PARTITION BY 1) AS Total
,Duration / sum(Duration) OVER (PARTITION BY 1) * 100 AS Distribution
,CASE
WHEN EventCategory < 0.05
THEN 'NOT INCL'
ELSE 'OK'
END AS Under3Min
FROM (
SELECT SystemName AS Machine
,EventDefinition
,EventDate
,EventStartDateTime
,IsNull(EventEndDateTime, GETDATE()) AS EventEndDateTime
,Sum(cast(EventEndDateTime - EventStartDateTime AS FLOAT)) * 24 AS Duration
,Sum(CASE
WHEN CustomEvent = 'without Stop'
THEN cast(EventEndDateTime - EventStartDateTime AS FLOAT) * 24
ELSE 0
END) AS EventCategory
FROM tDataCategory
WHERE EventDate >= #StartDateTime
AND EventDate <= #EndDateTime
AND SystemName = '201'
GROUP BY SystemName
,eventdefinition
,eventstartdatetime
,eventenddatetime
,EventDefinition
,EventDate
,CustomEvent
) AS t
WHERE CustomEvent <> 'without Stop'
OR (
CustomEvent = 'without Stop'
AND t.EventCategory >= 0.05
)
GROUP BY EventDefinition
,Duration
,Machine
,EventCategory
) A
INNER JOIN (
SELECT DataValue = CASE
WHEN Prod = 0
THEN 0
ELSE ISNULL(100.0 / Prod * Scrap, 0)
END
,Value = GoodUnits / TheoreticalUnits * 100
,NAME
FROM (
SELECT intervaldate AS DateValue
,intervalDateWeek AS Datum
,tsystem.NAME AS NAME
,ProductName AS Product
,teamname AS Team
,SUM(CASE
WHEN IssueName IN (
'A1'
,'A2'
)
THEN calculationUnitsInitial
ELSE 0
END) AS Scrap
,Sum(CASE
WHEN IssueName = 'Prod'
THEN calculationUnitsInitial
ELSE 0
END) AS Prod
,SUM(GoodUnits) AS GoodUnits
,SUM(TheoreticalUnits) AS TheoreticalUnits
,
FROM tCount
INNER JOIN tsystem ON tCount.systemid = tsystem.id
WHERE IntervalDate >= dateadd(wk, datediff(wk, 1, getdate()), 0)
AND IntervalDate <= dateadd(wk, datediff(wk, 0, getdate()), 0)
AND ((DATEPART(dw, IntervalDate) + ##DATEFIRST) % 7) NOT IN (
0
,1
)
AND tsystem.NAME = '201'
GROUP BY intervaldate
,tsystem.NAME
,intervaldateweek
,ProductName
,teamname
) AS s
) B ON A.Machine = B.NAME

Related

How to use where clause in Count Function?

i have a query in which i segregate old and new Employee i want to count how many New and old employees are there. how can i segregate and i dont want to use group by cluase.
here is my Query
((SELECT mock.EID,
mock.ECode,
mock.BaseCode,
mock.STATUS,
mock.EmpName,
mock.Desig,
mock.CMP_ID,
CASE WHEN podt.empid IS NULL THEN CAST(0 AS bit)ELSE CAST(1 AS bit)END AS [select],
CONVERT(varchar, mock.JoiningDate, 106) AS JoiningDate,
CASE
WHEN DATEDIFF(DAY, mock.JoiningDate, '1/31/' + CAST(DATEPART(YEAR, GETDATE()) AS varchar)) > 60 THEN 'Old'
ELSE 'New'
END AS StatusEmployee
FROM (SELECT E.EID,
E.ECode,
E.BaseCode,
CASE WHEN E.EActive = 0 THEN 'ACTIVE' ELSE 'IN ACTIVE' END AS STATUS,
E.EmpName,
D.DesigDesc AS Desig,
E.CMP_ID,
CAST(E.JoiningDate AS datetime) AS JoiningDate
FROM PostingDetail pd,
Employee_Profile E,
DESIGNATION D
WHERE pd.EmpId = E.EID
AND E.Desig = D.DesigCode
AND pd.SubLoc IN (6700, 20400, 21300, 21900)
AND pd.EndDate IS NULL
AND CMP_ID IN ('SZSPL')
AND CAST(E.JoiningDate AS datetime) BETWEEN CAST(E.JoiningDate AS datetime) AND '1/31/' + CAST(DATEPART(YEAR, GETDATE()) AS varchar)) mock
LEFT OUTER JOIN PostingDetail_training podt ON mock.EID = podt.empid));
select SUM (CASE WHEN tbl.StatusEmployee= 'New' then 1 else 0 end ) NewEmployee,SUM (CASE WHEN tbl.StatusEmployee= 'Old' then 1 else 0 end ) OldEmployee
from (
(select mock.EID, mock.ECode, mock.BaseCode, mock.STATUS, mock.EmpName, mock.Desig, mock.CMP_ID, case when podt.empid is null then cast(0 as bit) else cast(1 as bit) End [select] ,convert(varchar,mock.JoiningDate,106)JoiningDate,
case when DATEDIFF(day,mock.JoiningDate,'1/31/'+cast(DATEPART(year,getdate())as varchar)) > 60 then 'Old'
else 'New' end as StatusEmployee
from (
SELECT E.EID, E.ECode, E.BaseCode, CASE WHEN E.EActive = 0 THEN 'ACTIVE' ELSE 'IN ACTIVE' END AS STATUS, E.EmpName, D.DesigDesc As Desig, E.CMP_ID ,CAST(E.JoiningDate AS datetime) JoiningDate
FROM PostingDetail pd, Employee_Profile E, DESIGNATION D
Where pd.EmpId = E.EID AND E.Desig = D.DesigCode AND pd.SubLoc in(6700, 20400, 21300, 21900) AND pd.EndDate is null AND CMP_ID IN('SZSPL') and cast(E.JoiningDate as datetime) between cast(E.JoiningDate as datetime) and '1/31/'+cast(DATEPART(year,getdate())as varchar)) mock left outer join PostingDetail_training podt on mock.EID=podt.empid
)) tbl

How to use Join query between CTE and two tables?

I want to use a join query in CTE between two tables EmployeeDetails and MachineAttendance, but I'm confused - how will it be used?
;With CTE As
(
select ed.EmpName
from EmployeeDetails ed
)
,cte1; AS
(
select
ma.EmpID, cast(MA.Datetime as Date) as [Date],
case when MA.INOUT = 1 then DateTime end as INOUT_INTIME,
case when MA.INOUT = 2 then DateTime end as INOUT_OUTTIME
from
MachineAttendance MA
), cte2 as
(
select
EmpID, [Date],
MAX(INOUT_INTIME) AS INTIME,
MAX(INOUT_OUTTIME) AS OUTTIME,
DATEDIFF(Hour, MAX(INOUT_INTIME), MAX(INOUT_OUTTIME)) as [Hours]
from
CTE1
group by
EmpID, [Date]
)
select
EmpID, [Date], INTIME, OUTTIME, [Hours],
case
when [Hours] >= 8 then 1
when [Hours] = 0 then 0
when [Hours] >= 6 then 0.5
end as [Day],
case
when [Hours] > 8 then [Hours] - 8
else 0
end as OT,
case
when [Hours] >= 8
then ([Hours] - 8) * 100 else 0
end as OTAMount,
Convert(varchar(10), Date, 120) as [Date],
Convert(varchar(10), INTIME, 108) as [Time],
Case
When Convert(Time, INTIME, 108) > '09:10'
Then 1 else 0
end as Late
from
cte2
inner join
cte On cte.EmpID = cte2.EmpID`
You typed mixed syntax mysql and sql server and some extra comma was ther i think below will work
;With CTE As
(
select ed.EmpName from EmployeeDetails ed
)
,cte1 AS
(
SELECT ma.EmpID, CAST(MA.Datetime as Date) AS [Date],
CASE WHEN MA.INOUT = 1 THEN DateTime END AS INOUT_INTIME,
CASE WHEN MA.INOUT = 2 THEN DateTime END AS INOUT_OUTTIME
From
MachineAttendance MA
),
cte2
as
(
select EmpID, [Date], MAX(INOUT_INTIME) AS INTIME,
MAX(INOUT_OUTTIME) AS OUTTIME
, DATEDIFF(Hour, MAX(INOUT_INTIME), MAX(INOUT_OUTTIME)) as [Hours]
FROM CTE1
GROUP BY EmpID, [Date]
)
select EmpID, [Date], INTIME, OUTTIME, [Hours]
, CASE WHEN [Hours] >= 8 THEN 1
WHEN [Hours] = 0 THEN 0
WHEN [Hours] >= 6 THEN 0.5 END AS [Day],
CASE WHEN [Hours] > 8 then [Hours] - 8 else 0 End as OT,
CASE WHEN [Hours] >= 8
then ([Hours] - 8) * 100 else 0 END AS OTAMount,
Convert(varchar(10),Date,120) as [Date],
Convert(varchar(10),INTIME,108) as [Time],
Case When Convert(Time,INTIME,108) > '09:10' Then 1 else 0 end as Late
from cte2
INNER Join cte On cte.EmpID=cte2.EmpID

How to show monthly data even if there are no results yet SQL Server 2008

So I wrote a script that would show monthly premium. Say if you want to view the total premium up to November, you can pass through a parameter in in SSRS to pick 1/1/2016 - 11/30/2016. This would only show the data up until november, hoever, I would like to show it up until december even if there are no records there. How do I go about doing this in SQL? Here is my script so far:
SELECT lc.[Date]
,lc.Carrier
,lc.[Direct Ceded Written Premium]
,cast(cast(year(lc.[date]) as varchar(4)) + '-' + cast(month(lc.[date]) as varchar(2)) + '-01' as date) as [begofmonth]
from
(
SELECT
CASE
WHEN pd.TransactionEffDate < pd.TransactionDate THEN cast(pd.TransactionDate as DATE)
WHEN pd.TransactionEffDate < pd.EffectiveDate THEN cast(pd.EffectiveDate as DATE)
ELSE cast(pd.TransactionEffDate as date)
END AS [Date]
,CASE WHEN LEFT(PD.POLICYNUM, 3) = 'ORV'
THEN 'Palomar Value Select OR'
WHEN LEFT(PD.POLICYNUM, 3) = 'VSE'
THEN 'Palomar Value Select CA'
WHEN LEFT(PD.POLICYNUM, 3) = 'WAV'
THEN 'Palomar Value Select WA'
ELSE 'Palomar' END AS [Carrier]
,ISNULL(SUM(pd.WrittenPremium), 0) AS [Direct Ceded Written Premium]
FROM premdetail pd
JOIN transactionpremium tp ON pd.systemid = tp.systemid
AND pd.transactionpremiumid = tp.id
JOIN transactionhistory th ON tp.systemid = th.systemid
AND tp.cmmcontainer = th.cmmcontainer
AND tp.parentid = th.id
JOIN basicpolicy bp ON th.systemid = bp.systemid
AND th.cmmcontainer = bp.cmmcontainer
AND th.parentid = bp.id
WHERE
(CASE
WHEN pd.TransactionEffDate < pd.TransactionDate THEN pd.TransactionDate
WHEN pd.TransactionEffDate < pd.EffectiveDate THEN pd.EffectiveDate
ELSE pd.TransactionEffDate
END) > = CAST(#StartDate AS DATE)
AND (CASE
WHEN pd.TransactionEffDate < pd.TransactionDate THEN pd.TransactionDate
WHEN pd.TransactionEffDate < pd.EffectiveDate THEN pd.EffectiveDate
ELSE pd.TransactionEffDate
END) < CAST(#EndDate + 1 AS DATE)
AND (bp.carriercd = #ResEQCarrierCd
OR #ResEQCarrierCd = 'All')
GROUP BY
CASE
WHEN pd.TransactionEffDate < pd.TransactionDate THEN cast(pd.TransactionDate as DATE)
WHEN pd.TransactionEffDate < pd.EffectiveDate THEN cast(pd.EffectiveDate as DATE)
ELSE cast(pd.TransactionEffDate as date)
END
,CONVERT(VARCHAR, pd.EffectiveDate, 101)
,CONVERT(VARCHAR, pd.ExpirationDate, 101)
,CASE
WHEN LEFT(PD.POLICYNUM, 3) = 'ORV'
THEN 'Palomar Value Select OR'
WHEN LEFT(PD.POLICYNUM, 3) = 'VSE'
THEN 'Palomar Value Select CA'
WHEN LEFT(PD.POLICYNUM, 3) = 'WAV'
THEN 'Palomar Value Select WA'
ELSE 'Palomar'
END
,CASE
WHEN pd.TransactionCode = 'EN' THEN CONVERT(VARCHAR, th.TransactionEffectiveDt, 101)
ELSE ''
END
,CONVERT(VARCHAR, DATEADD(ms, -3, DATEADD(mm, DATEDIFF(m, 0, th.transactiondt) + 1, 0)), 101)
,CASE
WHEN pd.TransactionEffDate < CAST(CONVERT(VARCHAR, pd.TransactionDate, 101) AS SMALLDATETIME) THEN CONVERT(VARCHAR, pd.TransactionDate, 101)
WHEN pd.TransactionEffDate < pd.EffectiveDate THEN CONVERT(VARCHAR, pd.EffectiveDate, 101)
ELSE CONVERT(VARCHAR, pd.TransactionEffDate, 101)
END
) lc
ORDER BY lc.[Date], lc.[Carrier], lc.[Direct Ceded Written Premium]
With the parameter that I have, it would only show up until November. However, I would like it to show the whole year, up to December at in this case, even if there are no data there since I didn't pick the enddate variable to be december. I attached an example screenshot of what it should look like when exported to excel.
Just to give you an idea:
declare #tbl TABLE(ID INT IDENTITY,SomeValue VARCHAR(100),SomeDate DATE);
INSERT INTO #tbl VALUES('Some date in March',{d'2016-03-05'}),('Some date in June',{d'2016-06-30'});
WITH AllMonths AS
(
SELECT 1 AS MonthIndex
UNION ALL SELECT 2
UNION ALL SELECT 3
UNION ALL SELECT 4
UNION ALL SELECT 5
UNION ALL SELECT 6
UNION ALL SELECT 7
UNION ALL SELECT 8
UNION ALL SELECT 9
UNION ALL SELECT 10
UNION ALL SELECT 11
UNION ALL SELECT 12
)
SELECT MonthIndex
,t.*
FROM AllMonths
LEFT JOIN #tbl AS t ON MONTH(t.SomeDate)=MonthIndex
The result
1 NULL NULL NULL
2 NULL NULL NULL
3 1 Some date in March 2016-03-05
4 NULL NULL NULL
5 NULL NULL NULL
6 2 Some date in June 2016-06-30
7 NULL NULL NULL
8 NULL NULL NULL
9 NULL NULL NULL
10 NULL NULL NULL
11 NULL NULL NULL
12 NULL NULL NULL
There are many ways to create a tally table
CTE with ROW_NUMBER()
A list like in my example
A physical table
It is a good idea to maintain a numbers/DATE table!
In a previous answer I showed one way to create such a table.

How to breakdown time policy life period by beginning and end of the months

Picture. Need to be like that
I need to break down each policy life period by months. From the beginning of the policy till the end of that month, then from the beginning till the end of the next month and for each of this time period need to calculate the number of days, so then I can calculate earned premium for each policy.
Please see the picture what do I need to achieve.
[DECLARE #EarnedToDate datetime ='2016-06-30'
;WITH Cte_Policies AS
(
SELECT
PolicyNumber
,TransactionEffectiveDate
,TransactionExpirationDate
,WrittenPremium
,DATEDIFF(DAY,TransactionEffectiveDate,TransactionExpirationDate) AS TotalDays
,CASE
WHEN TransactionEffectiveDate> #EarnedToDate THEN 0 --Policy not yet in effect
WHEN TransactionExpirationDate< #EarnedToDate THEN DATEDIFF(DAY,TransactionEffectiveDate,TransactionExpirationDate)
ELSE DATEDIFF(DAY,TransactionEffectiveDate,#EarnedToDate)
END AS EarnedDays
,CASE
WHEN TransactionEffectiveDate > #EarnedToDate THEN DATEDIFF(DAY,TransactionEffectiveDate,TransactionExpirationDate)
WHEN TransactionExpirationDate < #EarnedToDate THEN 0 -- Policy completed
ELSE DATEDIFF(DAY,#EarnedToDate,TransactionExpirationDate)
END AS UnearnedDays
FROM ##TempTable1
)
SELECT PolicyNumber,
TransactionEffectiveDate as TransactionEffectiveDate,
TransactionExpirationDate as TransactionExpirationDate
--WrittenPremium/TotalDays AS DayPremium,
,SUM(CASE WHEN EarnedDays = 0 THEN 0 ELSE WrittenPremium/TotalDays * EarnedDays END) AS EarnedPremium
,SUM(CASE WHEN UnearnedDays = 0 THEN 0 ELSE WrittenPremium/TotalDays * UnearnedDays END) AS UnearnedPremium
FROM
Cte_Policies where PolicyNumber ='PACA1000238-02'
GROUP BY
TransactionEffectiveDate
,TransactionExpirationDate
--,WrittenPremium/TotalDays
,PolicyNumber][1]
My original snippet answered your question on Twitter, but the following code snippet takes the first one a bit further and provides exactly the result set specified on your question here on StackOverflow...
; WITH Earned_to_date AS (
SELECT Cast('2016-07-01' AS DATE) AS Earned_to_date
), policy_data AS (
SELECT
policy_number
, Cast(text_Effective AS DATE) AS TransactionEffectiveDate
, Cast(text_Expiration AS DATE) AS TransactionExpirationDate
, policy_premium
FROM (VALUES
('p1', '1993-01-01', '1994-12-31', 940.00)
, ('p3', '2011-12-01', '2012-05-31', 485.00)
, ('p5', '2011-12-16', '2012-05-15', 485.00)
, ('p7', '2015-12-16', '2016-11-15', 485.00)
) AS z (policy_number, text_Effective
, text_Expiration, policy_premium)
), digits AS (
SELECT digit
FROM (VALUES (0), (1), (2), (3), (4)
, (5), (6), (7), (8), (9)) AS z2 (digit)
), numbers AS (
SELECT 1000 * d4.digit + 100 * d3.digit + 10 * d2.digit + d1.digit AS number
FROM digits AS d1
CROSS JOIN digits AS d2
CROSS JOIN digits AS d3
CROSS JOIN digits AS d4
), calendar AS (
SELECT
DateAdd(month, number, '1753-01-01') AS month_of
, DateAdd(month, number, '1753-02-01') AS month_after
FROM numbers
), policy_dates AS (
SELECT
policy_number
, CASE
WHEN month_of < TransactionEffectiveDate THEN TransactionEffectiveDate
ELSE month_of
END AS StartRiskMonth
, CASE
WHEN TransactionExpirationDate < month_after THEN TransactionExpirationDate
WHEN Earned_to_date.Earned_to_date < month_after THEN Earned_to_date
ELSE month_after
END AS EndRiskMonth
, DateDiff(day, TransactionEffectiveDate, TransactionExpirationDate) AS policy_days
, policy_premium
FROM policy_data
JOIN calendar
ON (policy_data.TransactionEffectiveDate < calendar.month_after
AND calendar.month_of < policy_data.TransactionExpirationDate)
CROSS JOIN Earned_to_date
WHERE month_of < Earned_to_date
)
SELECT policy_number, StartRiskMonth, EndRiskMonth
, DateDiff(day, StartRiskMonth, EndRiskMonth) AS DaysInMonth
, policy_premium * DateDiff(day, StartRiskMonth, EndRiskMonth) / policy_days
FROM policy_dates
ORDER BY policy_number, StartRiskMonth
As I thought from your tweet, this is pretty simple to code but it takes a bit of work to understand.
WITH raw_data AS (
SELECT
Cast(text_TransactionEffectiveDate AS DATE) AS TransactionEffectiveDate
, Cast(text_TransactionExpirationDate AS DATE) AS TransactionExpirationDate
FROM (VALUES
('1953-01-15', '1992-02-23')
, ('2012-08-12', '2012-08-26')
) AS z (text_TransactionEffectiveDate, text_TransactionExpirationDate )
), policy_dates AS (
SELECT
raw_data.*
, DateAdd(month, DateDiff(month, '1753-01-01', TransactionEffectiveDate), '1753-01-01') AS Policy_Start
, DateAdd(month, DateDiff(month, '1753-01-01', TransactionExpirationDate), '1753-02-01') AS Policy_Expired
FROM raw_data
)
SELECT DateDiff(day, Policy_start, Policy_Expired) AS Policy_days, *
FROM policy_dates
This is a computation that is common in the insurance field. The trick lies in computing the beginning of the Effective Month, and the beginning of the expiration month (after the policy has ended). The trick is that at one point a month later than the others (1753-02-01) is used.
-PatP
Add a CTE or two that breaks the policy effective and expiration dates into distinct months, then re-use your existing code/CTE
Be sure to review all boundary conditions for EarnedDays and UnearnedDays and make sure they line up with your business rules
DECLARE #EarnedToDate DATETIME
SET #EarnedToDate = '2016-06-30'
DECLARE #tblPolicies TABLE
(
PolicyNumber VARCHAR(100)
, PolicyEffectiveDate DATETIME
, PolicyExpirationDate DATETIME
, WP MONEY --WrittenPremium
)
DECLARE #tblPolicyMonths TABLE
(
PolicyNumber VARCHAR(100),
MonthStart DATETIME,
MonthEnd DATETIME
)
DECLARE #CurPos INT
SET #CurPos = 1
WHILE #CurPos < 4000
BEGIN
--Create a bunch of policies
INSERT INTO #tblPolicies
SELECT 'P' + CONVERT(varchar, #CurPos), DATEADD(d, #CurPos, GETDATE()), DATEADD(YY, 1, DATEADD(d, #CurPos, GETDATE())), #CurPos
SET #CurPos = #CurPos + 1
END
DECLARE #LastPolicyDate DATETIME
SET #LastPolicyDate = (SELECT MAX(PolicyExpirationDate) FROM #tblPolicies)
;WITH Cte_All_Dates AS
(
SELECT MIN(PolicyEffectiveDate) DateValue
FROM #tblPolicies
UNION ALL
SELECT DateValue + 1
FROM Cte_All_Dates
WHERE DateValue + 1 < = #LastPolicyDate
)
INSERT INTO #tblPolicyMonths
SELECT P.PolicyNumber
,MIN(DateValue)
,MAX(DateValue)
FROM Cte_All_Dates PD
INNER JOIN #tblPolicies P
ON CONVERT(DATE, PD.DateValue) BETWEEN P.PolicyEffectiveDate AND P.PolicyExpirationDate
GROUP BY P.PolicyNumber
, DATEPART(MM, DateValue)
, DATEPART(YY, DateValue)
OPTION (MAXRECURSION 32767);
SELECT
P.PolicyNumber
,CONVERT(DATE, MonthStart) As StartRiskMonth
,CONVERT(DATE, MonthEnd) AS EndRiskMonth
,WP as WrittenPremium
,DATEDIFF(DAY,MonthStart,MonthEnd)+1 AS TotalDays
,CASE
WHEN MonthStart > #EarnedToDate THEN 0 --Policy not yet in effect
WHEN MonthEnd < #EarnedToDate THEN DATEDIFF(DAY,MonthStart,MonthEnd)+1
ELSE DATEDIFF(DAY,MonthStart,#EarnedToDate)+1
END AS EarnedDays
,CASE
WHEN MonthStart > #EarnedToDate THEN DATEDIFF(DAY,MonthStart,MonthEnd)+1
WHEN MonthEnd < #EarnedToDate THEN 0 -- Policy completed
ELSE DATEDIFF(DAY,#EarnedToDate,MonthEnd)
END AS UnearnedDays
, #EarnedToDate AS 'EarnedToDate'
FROM #tblPolicyMonths PM
INNER JOIN #tblPolicies P
ON PM.PolicyNumber = P.PolicyNumber
ORDER BY PolicyNumber, MonthStart, MonthEnd

Joining two queries into one

I have two working queries. Query 1 performs a filter on a large table and returns exactly the data that I need, it looks like this:
/****** QUERY #1 - This query will filter the data ******/
SELECT [WacnId],
[StartDT]
,[EndDT]
,[Group]
,[ID_Agency]
,[TargetUnit_Agency],
case [Group]
when 1 then 'in'
when 0 then 'out'
end as traffic
FROM [GW_20140315].[dbo].[ARC_Calls_ReportView]
WHERE [GroupDisplayID] = 'T802149' OR [ID_Agency] = 'Dispatch' or [TargetUnit_Agency] = 'Dispatch'
order by StartDT
Query #2 acts on the filtered data from Query 1 and produces a 1/2 hourly report. Query 2 looks like this:
/******Query #2- This query will take the filtered data and process it as needed ******/
SELECT dateadd(mi, (datediff(mi, 0, StartDT) / 30) * 30, 0) as HalfHour
, sum(DATEDIFF ( s , [StartDT] , [EndDT] )) as [Total Time (Seconds)],
SUM(CASE WHEN [TargetUnit_Agency] = 'Dispatch' then 1 ELSE 0 END ) AS InCount,
SUM(CASE WHEN [ID_Agency] = 'Dispatch' then 1 ELSE 0 END ) AS OutCount
FROM [Radio].[dbo].[Filter_Data]--This is how I did it before, but now I want to combine the two queries
GROUP BY dateadd(mi, (datediff(mi, 0, StartDT) / 30) * 30, 0)
ORDER BY 1
How may I combine these two queries into one?
You may use a CTE to describe your filtered data (first query) and then query using the CTE as your main table (second query):
;WITH FilteredCTE AS
(
SELECT [WacnId],
[StartDT]
,[EndDT]
,[Group]
,[ID_Agency]
,[TargetUnit_Agency],
case [Group]
when 1 then 'in'
when 0 then 'out'
end as traffic
FROM [GW_20140315].[dbo].[ARC_Calls_ReportView]
WHERE [GroupDisplayID] = 'T802149'
OR [ID_Agency] = 'Dispatch'
or [TargetUnit_Agency] = 'Dispatch'
)
SELECT dateadd(mi, (datediff(mi, 0, StartDT) / 30) * 30, 0) as HalfHour,
sum(DATEDIFF ( s , [StartDT] , [EndDT] )) as [Total Time (Seconds)],
SUM(CASE WHEN [TargetUnit_Agency] = 'Dispatch' then 1 ELSE 0 END ) AS InCount,
SUM(CASE WHEN [ID_Agency] = 'Dispatch' then 1 ELSE 0 END ) AS OutCount
FROM FilteredCTE
GROUP BY dateadd(mi, (datediff(mi, 0, StartDT) / 30) * 30, 0)
ORDER BY StartDT
Just select Query1 FROM Query2:
SELECT Dateadd(mi, ( Datediff(mi, 0, startdt) / 30 ) * 30, 0) AS HalfHour,
Sum(Datediff (s, [startdt], [enddt])) AS
[Total Time (Seconds)],
Sum(CASE
WHEN [targetunit_agency] = 'Dispatch' THEN 1
ELSE 0
end) AS InCount,
Sum(CASE
WHEN [id_agency] = 'Dispatch' THEN 1
ELSE 0
end) AS OutCount
FROM (SELECT [wacnid],
[startdt],
[enddt],
[group],
[id_agency],
[targetunit_agency],
CASE [group]
WHEN 1 THEN 'in'
WHEN 0 THEN 'out'
end AS traffic
FROM [GW_20140315].[dbo].[arc_calls_reportview]
WHERE [groupdisplayid] = 'T802149'
OR [id_agency] = 'Dispatch'
OR [targetunit_agency] = 'Dispatch'
ORDER BY startdt)
GROUP BY Dateadd(mi, ( Datediff(mi, 0, startdt) / 30 ) * 30, 0)
ORDER BY 1