UNION on 2 joined queries - sql

I have 2 working queries that are joined by subselects using WITH in DB2.
They each work separately but I can't seem to find the best way to properly combine or union them.
The first query:
with c as(
select
employee,
sum(salesPrice) as priorSpecifics
from schema1.orders g
inner join dateSchema.dates d
on g.dateField = d.dateField
where d.newDate between '2018-01-01' and '2018-01-31'
and g.details = 'CategoryOne'
group by employee
), d as(
select
employee,
sum(salesPrice) as priorTotals
from schema1.orders g
inner join dateSchema.dates d
on g.dateField = d.dateField
where d.newDate between '2018-01-01' and '2018-01-31'
group by employee
)
Select ifnull(c.employee,d.employee) as employee
,c.priorSpecifics
,d.priorTotals
,cast(Round((DEC(c.priorSpecifics,12,2)/DEC(d.priorTotals,12,2)) * 100,2) as decimal(12,2)) as priorPercent
from c full join d ON (c.employee = d.employee);
Returns 4 columns
and the 2nd query
with c as(
select
employee,
sum(salesPrice) as currentSpecifics
from schema1.orders g
inner join dateSchema.dates d
on g.dateField = d.dateField
where d.newDate between '2019-01-01' and '2019-01-31'
and g.details = 'CategoryOne'
group by employee
), d as(
select
employee,
sum(salesPrice) as currentTotals
from schema1.orders g
inner join dateSchema.dates d
on g.dateField = d.dateField
where d.newDate between '2019-01-01' and '2019-01-31'
group by employee
)
Select ifnull(c.employee,d.employee) as employee
,c.currentSpecifics
,d.currentTotals
,cast(Round((DEC(c.currentSpecifics,12,2)/DEC(d.currentTotals,12,2)) * 100,2) as decimal(12,2)) as currentPercent
from c full join d ON (c.employee = d.employee);
Returns 4 as well. The field employee is the only thing that is shared between all.
How can I combine this into one query to get one employee column and then all of my sum/percent columns following?

I think you can do everything you want with conditional aggregation:
select employee,
sum(case when d.newDate between '2018-01-01' and '2018-01-31' and g.details = 'CategoryOne' then salesPrice end) as priorSpecifics,
sum(case when d.newDate between '2019-01-01' and '2019-01-31' and g.details = 'CategoryOne' then salesPrice end) as currentSpecifics,
sum(case when d.newDate between '2018-01-01' and '2018-01-31' then salesPrice end) as priorTotals,
sum(case when d.newDate between '2019-01-01' and '2019-01-31' then salesPrice end) as currentTotals
from schema1.orders g inner join
dateSchema.dates d
on g.dateField = d.dateField
group by employee;
I'll let you fill in with the additional calculations.

If all the above queries are working then you already have everything you need.
You must combine from the 1st group, the first 2 to make the prior query, then
from the 2nd group to make the cur query
and finally join the prior query to the cur query:
with
c as(
select
employee,
sum(salesPrice) as priorSpecifics
from schema1.orders g
inner join dateSchema.dates d
on g.dateField = d.dateField
where d.newDate between '2018-01-01' and '2018-01-31'
and g.details = 'CategoryOne'
group by employee
),
d as(
select
employee,
sum(salesPrice) as priorTotals
from schema1.orders g
inner join dateSchema.dates d
on g.dateField = d.dateField
where d.newDate between '2018-01-01' and '2018-01-31'
group by employee
),
prior as (
Select ifnull(c.employee,d.employee) as employee
,c.priorSpecifics
,d.priorTotals
,cast(Round((DEC(c.priorSpecifics,12,2)/DEC(d.priorTotals,12,2)) * 100,2) as decimal(12,2)) as priorPercent
from c full join d ON (c.employee = d.employee)
),
e as(
select
employee,
sum(salesPrice) as currentSpecifics
from schema1.orders g
inner join dateSchema.dates d
on g.dateField = d.dateField
where d.newDate between '2019-01-01' and '2019-01-31'
and g.details = 'CategoryOne'
group by employee
),
f as(
select
employee,
sum(salesPrice) as currentTotals
from schema1.orders g
inner join dateSchema.dates d
on g.dateField = d.dateField
where d.newDate between '2019-01-01' and '2019-01-31'
group by employee
),
cur as (
Select ifnull(e.employee,f.employee) as employee
,e.currentSpecifics
,f.currentTotals
,cast(Round((DEC(e.currentSpecifics,12,2)/DEC(f.currentTotals,12,2)) * 100,2) as decimal(12,2)) as currentPercent
from e full join f ON (e.employee = f.employee)
)
Select ifnull(p.employee, c.employee) as employee
,p.priorSpecifics
,p.priorTotals
,p.priorPercent
,c.currentSpecifics
,c.currentTotals
,c.currentPercent
from prior p full join cur c ON (c.employee = c.employee);

Related

Pull top percent of IDs from a list based off of another CTE percentage

I have the below CTE to pull in membership then to pull in all claims for those members ( if they had a claim hit within the date parameters) , now from the total membership (=1961) I need to pull in the TOP 3% or 0.03 from the claims CTE. I see 1961*0.03 is rounded to 59, so I need to pull in the top (59) Medicaid IDs from Claims with the highest total of claims utilization .
So for example in the number_to_pull CTE that gives what lines need to pull in ( it gives the 3% of membership ), then in the sum_of_claims CTE I want to ONLY pull in the top 3% Medicaid IDs from Claims CTE.. Since the membership can change depending on the date parms I want the sum_of_claims to have something like the below but I am not sure how to get started
End result is I will have a list top (3%) of Medicaid IDs who have the most hits per claim for the date span called out
I need something like this, but I want it to pull in whatever the number is in the number_to_pull CTE and then to pull That number based off of the sum of claims.
Select Top ( select
round(count(mt.medicaid_no)*0.03) as percentt
from membership mt)
cll.medicaid_no
,count(distinct claim_number) as sum_of_claims
from claims cll
Group by cll.medicaid_no
) select * from sum_of_claims
This is what my codes actually looks like
WITH
DATES AS
(
select TRUNC(TRUNC(SYSDATE,'y')-1,'y') as startdate,
TRUNC(SYSDATE,'y')-1 as enddate
from dual
),
membership as (
select Distinct
mbr.medicaid_no
,mbd.memb_dim_id
,mbd.memb_demographics_full_date
from dw.fact_member_demographics mbd
inner join dates d
on 1=1
inner join dw.DIM_MEMBER mbr
on mbd.memb_dim_id = mbr.memb_dim_id
Where EXTRACT(YEAR FROM mbd.memb_demographics_full_date)= extract(year from d.startdate)
and mbd.company_dim_id in ('575')
and mbd.age > 18
) ---select * from membership
,number_to_pull as (
select
round(count(mt.medicaid_no)*0.03) as percentt
from membership mt
) ---select * from top_number
,Claims as (
select
mbdd.medicaid_no
,mbdd.memb_dim_id
,dc.company_desc
,cl.primary_svc_date
,cl.claim_number
,case when cl.io_flag_dim_id = '1' then 'Inpatient'
when cl.io_flag_dim_id = '2' then 'Outpatient' else 'false' end as In_Op
,cl.admit_type
,proc.procedure_code
,dx1.diagnosis_code as dx1
,dx1.diagnosis_short_desc as dx1desc
,dx2.diagnosis_code as dx2
,dx2.diagnosis_short_desc as dx2desc
,dx3.diagnosis_code as dx3
,dx3.diagnosis_short_desc as dx3desc
,dx4.diagnosis_code as dx4
,dx4.diagnosis_short_desc as dx4desc
,dx5.diagnosis_code as dx5
,dx5.diagnosis_short_desc as dx5desc
,bt.inp_outp_ind
from membership mbdd
left join dw.fact_claim cl
on mbdd.memb_dim_id = cl.memb_dim_id
inner join dates d
on 1=1
inner join dw.DIM_PROCEDURE_CODE proc
on cl.cpt_code_dim_id = proc.procedure_dim_id
inner join dw.DIM_DIAGNOSIS dx1
on cl.diagnosis_1_dim_id = dx1.diagnosis_dim_id
inner join dw.DIM_DIAGNOSIS dx2
on cl.diagnosis_2_dim_id = dx2.diagnosis_dim_id
inner join dw.DIM_DIAGNOSIS dx3
on cl.diagnosis_3_dim_id = dx3.diagnosis_dim_id
inner join dw.DIM_DIAGNOSIS dx4
on cl.diagnosis_4_dim_id = dx4.diagnosis_dim_id
inner join dw.DIM_DIAGNOSIS dx5
on cl.diagnosis_5_dim_id = dx5.diagnosis_dim_id
inner join dw.DIM_BILL_TYPE bt
on cl.bill_type_dim_id = bt.bill_type_dim_id
inner join dw.DIM_COMPANY dc
on cl.company_dim_id = dc.company_dim_id
Where cl.primary_svc_date between d.startdate and d.enddate
and cl.company_dim_id in ('575')
and CL.WHOLE_CLAIM_STATUS_DIM_ID IN (1,2)
and cl.io_flag_dim_id in ('1','2')
) ---select * from claims
,sum_of_claims AS (
Select
---- this is where I want to pull in the top 3% based off of membeship and sum of claims per Medicaid
cll.medicaid_no
,count(distinct claim_number) as sum_of_claims
from claims cll
Group by cll.medicaid_no
) select * from sum_of_claims
The end result I want is a list of Medicaid IDs and there total sum of claims, but this list will ONLY be the top 59 lines (3%)
MEDICAID_NO SUM_OF_CLAIMS
111111 $12,439.61
333333 $5,315.57
444444 $2,007.00
555555 $1,823.98
888888 $1,770.00
777777 $1,211.47
9999999 $1,157.61
6666666 $1,068.76
If I read your question, correctly, you want to get the top 3% here? This is the final query:
select * from sum_of_claims;
I think you want to replace this with something like the following:
SELECT medicaid_no, sum_of_claims FROM (
SELECT medicaid_no, sum_of_claims, COUNT(*) OVER () AS total_cnt
, ROW_NUMBER() OVER ( ORDER BY sum_of_claims DESC ) AS rn
FROM sum_of_claims
) WHERE rn <= 0.03 * total_cnt;
This will get the "top" 3% of records (where "top" is defined as those with the greatest claim amounts).
By the way, I find it hard to believe that this is what you want:
,count(distinct claim_number) as sum_of_claims
That wouldn't give a sum at all!
Hope this helps.
Thanks David F. I was able to pull in the top 3% members from claims . Below is my code .
WITH
DATES AS
(
select TRUNC(TRUNC(SYSDATE,'y')-1,'y') as startdate,
TRUNC(SYSDATE,'y')-1 as enddate
from dual
),
membership as (
select Distinct
mbr.medicaid_no
,mbd.memb_dim_id
,mbd.memb_demographics_full_date
from dw.fact_member_demographics mbd
inner join dates d
on 1=1
inner join dw.DIM_MEMBER mbr
on mbd.memb_dim_id = mbr.memb_dim_id
Where EXTRACT(YEAR FROM mbd.memb_demographics_full_date)= extract(year from d.startdate)
and mbd.company_dim_id in ('575')
and mbd.age > 18
) ---select * from membership
,Claims as (
select
mbdd.medicaid_no
,mbdd.memb_dim_id
,dc.company_desc
,cl.primary_svc_date
,cl.claim_number
,case when cl.io_flag_dim_id = '1' then 'Inpatient'
when cl.io_flag_dim_id = '2' then 'Outpatient' else 'false' end as In_Op
,cl.admit_type
,proc.procedure_code
,dx1.diagnosis_code as dx1
,dx1.diagnosis_short_desc as dx1desc
,dx2.diagnosis_code as dx2
,dx2.diagnosis_short_desc as dx2desc
,dx3.diagnosis_code as dx3
,dx3.diagnosis_short_desc as dx3desc
,dx4.diagnosis_code as dx4
,dx4.diagnosis_short_desc as dx4desc
,dx5.diagnosis_code as dx5
,dx5.diagnosis_short_desc as dx5desc
,bt.inp_outp_ind
,cl.net_amt
from membership mbdd
left join dw.fact_claim cl
on mbdd.memb_dim_id = cl.memb_dim_id
inner join dates d
on 1=1
inner join dw.DIM_PROCEDURE_CODE proc
on cl.cpt_code_dim_id = proc.procedure_dim_id
inner join dw.DIM_DIAGNOSIS dx1
on cl.diagnosis_1_dim_id = dx1.diagnosis_dim_id
inner join dw.DIM_DIAGNOSIS dx2
on cl.diagnosis_2_dim_id = dx2.diagnosis_dim_id
inner join dw.DIM_DIAGNOSIS dx3
on cl.diagnosis_3_dim_id = dx3.diagnosis_dim_id
inner join dw.DIM_DIAGNOSIS dx4
on cl.diagnosis_4_dim_id = dx4.diagnosis_dim_id
inner join dw.DIM_DIAGNOSIS dx5
on cl.diagnosis_5_dim_id = dx5.diagnosis_dim_id
inner join dw.DIM_BILL_TYPE bt
on cl.bill_type_dim_id = bt.bill_type_dim_id
inner join dw.DIM_COMPANY dc
on cl.company_dim_id = dc.company_dim_id
Where cl.primary_svc_date between d.startdate and d.enddate
and cl.company_dim_id in ('575')
and CL.WHOLE_CLAIM_STATUS_DIM_ID IN (1,2) -- pulling in only paid claims -- use whole claim
and cl.io_flag_dim_id in ('1','2')
) ---select * from claims
,sum_of_claims AS (
Select
cll.medicaid_no
,sum(distinct cll.net_amt) as sum_of_claims
from claims cll
Group by cll.medicaid_no
)
----- this is the new part added below
SELECT medicaid_no, sum_of_claims FROM (
SELECT sh.medicaid_no, sh.sum_of_claims, COUNT(*) OVER () AS total_cnt
, ROW_NUMBER() OVER ( ORDER BY sh.sum_of_claims DESC ) AS rn
FROM sum_of_claims sh
)
Where (rn)<(SELECT round(count(medicaid_no)*0.03) as percentt
from membership)

How to combine results of 3 Joins?

I am trying to make a table per employee that will give the information per employee that was present/absent/work from home.For that I am writing a SQL query that is fetching the records using JOINS. However, I am writing 3 Join statements that are returning me data separately. How can I write a query that will return the results of the 3 subsequent joins in one single (SELECT)query? Here are the Join statements:
Select EmployeeId, Employees.Name, COUNT(*) [Absent]
From Attendances
Left Join Employees
On Employees.EmployeeId = Attendances.EmpID And Attendances.IsAbsent = 1 and Employees.Name = 'John'
Where CAST(Attendances.InDateTime as Date) >= '2016-06-19 10:00:00.000'
Group By EmployeeId, Employees.Name
select Employees.Name, COUNT(*) [Present]
from Employees
Inner Join Attendances
On Employees.UserId = Attendances.EmpID and Attendances.IsAbsent = 0
Where CAST(Attendances.InDateTime as Date) >= '2017-06-19 10:00:00.000' and Employees.Name='John'
Group By Employees.Name
select Employees.Name, COUNT(*) [WorkFromHome]
from Employees
Inner Join Attendances
On Employees.UserId = Attendances.EmpID and Attendances.IsWorkFromHome = 1
Where CAST(Attendances.InDateTime as Date) >= '2017-06-19 10:00:00.000' and Employees.Name='John'
Group By Employees.Name
The current output that I am getting is:
Name|Present, Name|Absent, Name|WorkFromHome
But I want it as:
Name|Present|Absent|WorkFromHome
Use Subqueries to get your desired outputs:
SELECT T1.ID,
T1.Name,
T1.[Absent],
T2.[Present],
T3.[WorkFromHome]
FROM
(
select ID, Employees.Name, COUNT(*) [Absent]
from Employees
Inner Join Attendances
On Employees.UserId = Attendances.EmpID and Attendances.IsAbsent = 1
Where CAST(Attendances.InDateTime as Date) >= '2017-06-19 10:00:00.000' and Employees.Name='John'
Group By Employees.Name, ID
) T1 JOIN
(
select ID, Employees.Name, COUNT(*) [Present]
from Employees
Inner Join Attendances
On Employees.UserId = Attendances.EmpID and Attendances.IsAbsent = 0
Where CAST(Attendances.InDateTime as Date) >= '2017-06-19 10:00:00.000' and Employees.Name='John'
Group By Employees.Name, ID
) T2 ON T1.ID = T2.ID JOIN
(
select ID, Employees.Name, COUNT(*) [WorkFromHome]
from Employees
Inner Join Attendances
On Employees.UserId = Attendances.EmpID and Attendances.IsWorkFromHome = 1
Where CAST(Attendances.InDateTime as Date) >= '2017-06-19 10:00:00.000' and Employees.Name='John'
Group By Employees.Name, ID
) T3 ON T2.ID = T3.ID;
You can use UNION or UNION ALL. For Example
SELECT * FROM TABLE WHERE NAME = 'Mohit'
UNION ALL
SELECT * FROM TABLE WHERE NAME = 'Jhon'
UNION ALL
SELECT * FROM TABLE WHERE NAME = 'Jeni'
UNION ALL will return unique records. However UNION will return all the record.
Use UNION ALL to get combined data like this
select Employees.Name, 'A' Attendance, COUNT(*) [Count]
from Employees
Inner Join Attendances
On Employees.UserId = Attendances.EmpID and Attendances.IsAbsent = 1
Where CAST(Attendances.InDateTime as Date) >= '2017-06-19 10:00:00.000' and
Employees.Name='John'
Group By Employees.Name
UNION ALL
select Employees.Name, 'P' Attendance, COUNT(*) [Count]
from Employees
Inner Join Attendances
On Employees.UserId = Attendances.EmpID and Attendances.IsAbsent = 0
Where CAST(Attendances.InDateTime as Date) >= '2017-06-19 10:00:00.000' and
Employees.Name='John'
Group By Employees.Name
UNION ALL
select Employees.Name, 'WFH' Attendance, COUNT(*) [Count]
from Employees
Inner Join Attendances
On Employees.UserId = Attendances.EmpID and Attendances.IsWorkFromHome = 1
Where CAST(Attendances.InDateTime as Date) >= '2017-06-19 10:00:00.000' and
Employees.Name='John'
Group By Employees.Name

SQL Inner join group... missing expression

I have following query, which works fine:
SELECT c.id, c.customer_name, b.batch_prefix, b.BatchCount, b.InvoiceCount, e.time_of_delivery, e.time_of_delivery_mail, e.time_of_delivery_clock
FROM koll_customers c
INNER JOIN (
SELECT batch_prefix, COUNT(*) AS BatchCount,
SUM (batch_counter) AS InvoiceCount
FROM koll_batchlogs
WHERE
exists_db = 0
and is_checked = 1
and batch_counter > 0
and trunc(created_date) > trunc(sysdate-7)
GROUP BY batch_prefix) b
ON b.batch_prefix=c.customer_prefix
INNER JOIN (
SELECT id, time_of_delivery, time_of_delivery_mail, time_of_delivery_clock
FROM koll_customer_export) e
ON e.id = c.id
My requirement is to add another column 'YellowCategory'. For that I tried to change the query to following:
SELECT c.id, c.customer_name, b.batch_prefix, b.BatchCount, b.InvoiceCount, e.time_of_delivery, e.time_of_delivery_mail, e.time_of_delivery_clock, e.YellowCategory
FROM koll_customers c
INNER JOIN (
SELECT batch_prefix, COUNT(*) AS BatchCount,
SUM (batch_counter) AS InvoiceCount
FROM koll_batchlogs
WHERE
exists_db = 0
and is_checked = 1
and batch_counter > 0
and trunc(created_date) > trunc(sysdate-7)
GROUP BY batch_prefix) b
ON b.batch_prefix=c.customer_prefix
INNER JOIN (
SELECT id, time_of_delivery, time_of_delivery_mail, time_of_delivery_clock, COUNT(b.batch_counter) AS YellowCategory,
FROM koll_customer_export
WHERE to_date(created_date,'DD.MM.RRRR HH24:MI:SS') < to_date(sysdate-time_of_delivery,'DD.MM.RRRR HH24:MI:SS')
GROUP BY b.batch_counter) e
ON e.id = c.id
But then I get "missing expression" error. I guess in last INNER JOIN. Don't know where is the problem... Any help?
Update
With following query, I get b.batch_counter invalid identifier error now.
SELECT c.id, c.customer_name, b.batch_prefix, b.BatchCount,
b.InvoiceCount, e.time_of_delivery, e.time_of_delivery_mail,
e.time_of_delivery_clock, e.YellowCategory
FROM koll_customers c
INNER JOIN (
SELECT batch_prefix, batch_counter, COUNT(*) AS BatchCount,
SUM (batch_counter) AS InvoiceCount
FROM koll_batchlogs
WHERE exists_db = 0 and is_checked = 1
and batch_counter > 0 and trunc(created_date) > trunc(sysdate-7)
GROUP BY batch_prefix
) b
ON b.batch_prefix=c.customer_prefix
INNER JOIN (
SELECT id, time_of_delivery, time_of_delivery_mail,
time_of_delivery_clock,
COUNT(b.batch_counter) AS YellowCategory
FROM koll_customer_export
WHERE to_date(created_date,'DD.MM.RRRR HH24:MI:SS')
< to_date(sysdate- time_of_delivery,'DD.MM.RRRR HH24:MI:SS')
GROUP BY b.batch_counter
) e
ON e.id = c.id
Is this the query you want?
SELECT c.id, c.customer_name, b.batch_prefix, b.BatchCount, b.InvoiceCount,
e.time_of_delivery, e.time_of_delivery_mail, e.time_of_delivery_clock, e.YellowCategory
FROM koll_customers c INNER JOIN
(SELECT batch_prefix, COUNT(*) AS BatchCount, SUM (batch_counter) AS InvoiceCount
FROM koll_batchlogs
WHERE exists_db = 0 and is_checked = 1 and batch_counter > 0 and
trunc(created_date) > trunc(sysdate-7)
GROUP BY batch_prefix
) b
ON b.batch_prefix = c.customer_prefix INNER JOIN
(SELECT id, time_of_delivery, time_of_delivery_mail, time_of_delivery_clock,
COUNT(*) AS YellowCategory,
FROM koll_customer_export
WHERE to_date(created_date, 'DD.MM.RRRR HH24:MI:SS') < to_date(sysdate-time_of_delivery,'DD.MM.RRRR HH24:MI:SS')
GROUP BY id, time_of_delivery, time_of_delivery_mail, time_of_delivery_clock
) e
ON e.id = c.id;
It is impossible for me to say if this is what you really need. But I think the query will at least compile so you can run it.. The where clause in the e subquery looks really strange. Why would you be converting a date column into a date column using to_date()?
You typed one comma too much at the end of the SELECT list inside the last INNER JOIN.

How to insert into one table from multiple table while using UNION

I have the following query which queries different table and uses the UNION operator to display a set of data:
-----TOTAL COUNT OF ACTIVE DEA----- DEA
select attr1671 as 'TYPE', count(attr1668) as 'TOTAL'
from [MyServer].[DBOTYPE].instance.rmobjectinsta d inner join (select fk1665, max(objectid) 'newobjectid'
from [MyServer].[DBOTYPE].instance.rmobjectinsta
group by fk1665) n on d.objectid = n.newobjectid where attr1671 = 'DEA' and cast(attr1668 as date) > cast(getdate()+30 as date) and activestatus = 0
group by attr1671
-----TOTAL COUNT OF ACTIVE LICENSES----- LICENSE
UNION
select 'LICENSE' as 'TYPE', count(*) as 'TOTAL'
from [MyServer].[DBOTYPE].instance.rmobjectin t inner join (select fk1656, max(objectid) 'newobjectid'
from [MyServer].[DBOTYPE].instance.rmobjectin
group by fk1656) c on t.objectid = c.newobjectid where cast(attr1660 as date) > cast(getdate()+30 as date) and activestatus = 0
-----TOTAL INFECTION CERTIFICATIONS ACTIVE----- INFECTION
UNION
select 'INFECTION' as 'TYPE', count(*) 'TOTAL'
from [MyServer].[DBOTYPE].instance.rmobject z inner join (select fk1676, max(objectid) 'newobjectid'
from [MyServer].[DBOTYPE].instance.rmobject
group by fk1676) h on z.objectid = h.newobjectid where cast(attr1680 as date) > cast(getdate()+30 as date) and activestatus = 0
-----TOTAL COUNT OF ACTIVE CDS----- CDS
UNION
select attr1671 as 'TYPE', count(attr1668) as 'TOTAL'
from [MyServer].[DBOTYPE].instance.rmobje k inner join (select fk1665, max(objectid) 'newobjectid'
from [MyServer].[DBOTYPE].instance.rmobje
group by fk1665) l on k.objectid = l.newobjectid where attr1671 = 'CDS' and cast(attr1668 as date) > cast(getdate()+30 as date) and activestatus = 0
group by attr1671
Which displays the following:
TYPE TOTAL
CDS 45
DEA 56
INFECTION 67
LICENSE 41
I would like to insert the data into a table that I can import as a DataSet in my SSRS report. How can I achieve it?
I tried doing the following:
-----TOTAL COUNT OF ACTIVE DEA----- DEA
select attr1671 as 'TYPE', count(attr1668) as 'TOTAL'
INTO [MYDB].[DBO].[myT] --on first run and then comment
from [MyServer].[DBOTYPE].instance.rmobjectinsta d inner join (select fk1665, max(objectid) 'newobjectid'
from [MyServer].[DBOTYPE].instance.rmobjectinsta
group by fk1665) n on d.objectid = n.newobjectid where attr1671 = 'DEA' and cast(attr1668 as date) > cast(getdate()+30 as date) and activestatus = 0
group by attr1671
-----TOTAL COUNT OF ACTIVE LICENSES----- LICENSE
UNION
select 'LICENSE' as 'TYPE', count(*) as 'TOTAL'
INTO [MYDB].[DBO].[myT] --on first run and then comment
from [MyServer].[DBOTYPE].instance.rmobjectin t inner join (select fk1656, max(objectid) 'newobjectid'
from [MyServer].[DBOTYPE].instance.rmobjectin
group by fk1656) c on t.objectid = c.newobjectid where cast(attr1660 as date) > cast(getdate()+30 as date) and activestatus = 0
-----TOTAL INFECTION CERTIFICATIONS ACTIVE----- INFECTION
UNION
select 'INFECTION' as 'TYPE', count(*) 'TOTAL'
INTO [MYDB].[DBO].[myT] --on first run and then comment
from [MyServer].[DBOTYPE].instance.rmobject z inner join (select fk1676, max(objectid) 'newobjectid'
from [MyServer].[DBOTYPE].instance.rmobject
group by fk1676) h on z.objectid = h.newobjectid where cast(attr1680 as date) > cast(getdate()+30 as date) and activestatus = 0
-----TOTAL COUNT OF ACTIVE CDS----- CDS
UNION
select attr1671 as 'TYPE', count(attr1668) as 'TOTAL'
INTO [MYDB].[DBO].[myT] --on first run and then comment
from [MyServer].[DBOTYPE].instance.rmobje k inner join (select fk1665, max(objectid) 'newobjectid'
from [MyServer].[DBOTYPE].instance.rmobje
group by fk1665) l on k.objectid = l.newobjectid where attr1671 = 'CDS' and cast(attr1668 as date) > cast(getdate()+30 as date) and activestatus = 0
group by attr1671
But that didn't work. Please help...
This is the error I get:
Msg 196, Level 15, State 1, Line 2
SELECT INTO must be the first query in a statement containing a UNION, INTERSECT or EXCEPT operator.
You can try wrapping the whole thing as a subselect:
select *
into <whatever>
from (<your query here>
) t;
Try this :
With Emp_CTE (Employee,Count)
AS
(
Select Firstname as Employee , Count(*) as Count from Employee
where FirstName like 'V%'
group by FirstName
union
Select Firstname as Employee , Count(*) as Count from Employee
where FirstName like 'M%'
group by FirstName
)
Select * into dbo.EmployeeCount from Emp_CTE;

Is this possible to simplify this SQL query?

I have designed the following sql query to get the percentage of
100 - ((reportedDate – Submission Date) / TotalNumOfVisits) * 100
Is there any way to simplify it? Like combine the two queries into one?
SELECT
q1.VisitMonth,q1.TotalVisit, ISNULL(q2.diff,0) AS DIFF
,100 - ISNULL( (CAST((q2.diff * 1.0 / q1.TotalVisit ) * 100 AS FLOAT)),0) PERC
FROM
(
SELECT DATENAME(MONTH,v.VisitDate) as VisitMonth, count(v.VisitID) as TotalVisit
FROM Visits v
INNER JOIN Assignments a ON a.AssignmentID = v.AssignmentID
WHERE a.ClientID IN (33,46)
AND v.VisitDate BETWEEN '01/01/2013' AND '31/12/2013'
group by DATENAME(MONTH,v.VisitDate)
) q1
LEFT OUTER JOIN
(
SELECT DATENAME(MONTH,v.VisitDate) as MonthName,COUNT(*) as diff
FROM Visits v
INNER JOIN Assignments a ON a.AssignmentID = v.AssignmentID
WHERE a.ClientID IN (33,46)
AND v.VisitDate BETWEEN '01/01/2013' AND '31/12/2013'
AND DATEDIFF(DAY,v.ReportDate,v.SubmissionDate) > 2
group by DATENAME(MONTH,v.VisitDate)
) q2
ON q1.VisitMonth = q2.MonthName
Result:
Try this :-
Select
VisitMonth,isnull(diff,0) as DIFF,
100 - ISNULL( (CAST((diff * 1.0 / Nullif(TotalVisit,0) ) * 100 AS FLOAT)),0) PERC
from
(
SELECT
VisitMonth = Datename(month,visitDate) ,
Diff = Sum(case when DATEDIFF(DAY,v.ReportDate,v.SubmissionDate) > 2 then 1
else 0 end) ,
TotalVisit = Count(v.VisitID)
FROM Visits v
INNER JOIN Assignments a ON a.AssignmentID = v.AssignmentID
WHERE a.ClientID IN (33,46)
AND v.VisitDate BETWEEN '01/01/2013' AND '31/12/2013'
group by DATENAME(MONTH,v.VisitDate)
)a