Sum a UNION query
URGENT PLS!!
hi,
pls im trying to query my database but i dont know how to write the query. here is what i was told to do.
there are 3 tables,
1. HCP table that hold all the name of hospitals (primary key is HCP_ID)
2. EMPLOYEE table, which hold the info about employee (primary key is EMP_ID and foreign key is HCP_ID)
3.DEPENDANT table which hold info about the families(dependants) of an EMPLOYEE (primary key is DEP_ID, foreign key is EMP_ID)
now my boss wants a report on the hospitals(HCP) that have 1-499 number of lives.(lives, i mean employee and dependant) which should include the name of the hospital and the count of lives in each hospital as the only 2 colunm. thanks
Edited by: tiana on Jul 11, 2011 3:17 AM
Something like this;
select h.HCP_Name as Hospital_Name
,e.cn as Number_of_Lives
from HCP h
,(select e.hcp_id
,count(1) over (partition by e.hcp_id) cn
from Employees e
,Dependant d
where e.Emp_ID = d.Emp_ID) e
where e.cn > 0 and e.cn < 500
and h.hcp_id = e.hcp_id
/Edited by: bluefrog on Jul 11, 2011 11:42 AM
Similar Messages
-
hi, i am using oracle 10g database..
how to get the sum of column in union query ?
select * from (select 100 records from dual), (select 50 available from dual)
union
select * from (select 200 records from dual), (select 150 available from dual)
display should be like
records available
100 50
200 150
total 300 200thanks ...Peter vd Zwan wrote:
try this:Grouping by records will not produce correct results:
SQL> with a as
2 (
3 select * from (select 100 records from dual), (select 50 available from dual)
4 union
5 select * from (select 100 records from dual), (select 100 available from dual)
6 union
7 select * from (select 200 records from dual), (select 150 available from dual)
8 )
9 select
10 case when grouping(records) = 0 then null else 'total' end tot
11 ,sum(records) records
12 ,sum(available) available
13 from
14 a
15 group by
16 rollup (records)
17 ;
TOT RECORDS AVAILABLE
200 150
200 150
total 400 300
SQL> select case grouping(rownum)
2 when 1 then 'Total'
3 end display,
4 sum(records) records,
5 sum(available) available
6 from (
7 select * from (select 100 records from dual), (select 50 available from dual)
8 union
9 select * from (select 100 records from dual), (select 100 available from dual)
10 union
11 select * from (select 200 records from dual), (select 150 available from dual)
12 )
13 group by rollup(rownum)
14 /
DISPL RECORDS AVAILABLE
100 50
100 100
200 150
Total 400 300
SQL> SY. -
How to get Average of a column in UNION query
Hi All,
I will try to explain the issue as much as I can and If you need clarification on any piece please let me know.
So, I have a Union Query with two sets of Criteria.
The first Criteria Brings the list of Buildings and a set of Measures for it. The second criteria does the same but with a different set of filters.
No I use a UNION between these both criteria and present them in a Pivot view so that we only have one row per each building. The values in each of the criteria in the UNION query are Summed
Ex:
Building
Metric 1
Metric 2
1
20
30
1
25
35
2
40
50
2
45
55
So as I show in the pivot the result is
Building
Metric 1
Metric 2
1
45
65
2
85
105
Now the issue is with the Grand Total.
I want the Grand Total to be an Average of the Buildings. So for Metric 1 The Grand Total should be (45+85)/2 because we have two buildings so the answer should be 65.
How can I get that.
Bottom Line: Need an Average as the Grand Total when the Aggregation rule on the column is set to Sum.
we use 11.1.6.10 versionHi VJ
What you are asking is impossible in the pivot table itself as you are asking one part of the pivot table to aggregate via one method, and another to aggregate via another method, on the same column ..
It can be done using a calculated item. For your example above you'd use the formula ( $1 + $2) / 2.
.. But thats HIGHLY explicit, and would only work if you KNOW how many buildings will come back in the query.. EVERYTIME.
Why not restructure the query to combine it into a single query using an combinations of filters with OR in between? -
Hi Guys,
I want to know how to create parameter in case of union query in 8.8. with new token option.
Thanks RashidHi Rashid,
It seems you are asking question regarding Crystal Report. Is that true?
Thanks,
Gordon -
All,
How to create a view using a union query in sql developer. I tried doing but when i check the syntax I got an error
"The SQL syntax is valid, however the query is invalid or uses functionality that is not supported.
Declarative query support does not currently include UNION, INTERSECT or MINUS"
Could some one help me out
Regards792011 wrote:
All,
How to create a view using a union query in sql developer. I tried doing but when i check the syntax I got an error
"The SQL syntax is valid, however the query is invalid or uses functionality that is not supported.
Declarative query support does not currently include UNION, INTERSECT or MINUS"
Could some one help me outuse different/upgraded client since UNION is valid SQL -
Prompts for Combine similar request (Union query)
I have been given 5 tables for creating one report out of each table. I created aliases and
necessary self joins. I now need a summaryreport that combines these five tables. I tried the
"combine similar request" and the report functions fine. Now I have to create two prompts, one for
country and one for job. These are fields available in 4 tables and have the same format alongwith
the same datatypes. Please help me with this.
Table 1 Report A
Table 2 Report B
Table 3 Report C
Table 4 Report D
Table 5 Report E
Table 1 - Table 4 contains Country and Job field which is of the same format and datatype.
Table 5 does not have these and its not necessary for us to prompt this.
This has no star schema setup and I am not in a position to get it done as well. I considered each
table to be a fact table and created aliases, selfjoins etc. Please help with the procedure to
create the two dashboard prompts. If I choose USA then the first four amongst the union queries
should reflect data for the USA. The same applies for Job.Hello
Thanks for the reply.
My problem here is that I have 5 different tables with country fields in them. They are of the same format and datatype but there is no join between these tables. If I choose one Country field from any particular table, then the combine similar request doesnt seem to take it for other queries where the fields come from a different table.
eg.
Table 1 - table 5 have country fields
I choose to create a prompt based on Country from Table 1. The union query doesnt seem to reflect on filtering values on the queries from other tables. It would filter only the values from table 1.
Please let me know as to what can be done! -
Alternative/enhancement to union query? Duplicate - please delete
Hello,
I have 2 sets of similar data which I am joining together with a union query.
Simplified E.g.
*Table A*
Name Dept
Ben 1
Amy 3
Ken 3
*Table B*
Name Dept
Jim 1
John 2
Sue 3
select Name, Dept
from table A
UNION
select Name, Dept
from table BWhat I would like to do is ONLY include data from the second part of the union query where it joins with some data from the first part of the union query.
E.g.
select Name, Dept
from table A
UNION
select Name, Dept
from table B
where Dept in (select distinct Dept from A)Therefore John that works in Dept 2 would not be included in the results.
Is there a better or more efficient way of doing this than my example using the subquery as part of the where clause?
Many thanks,
Hazel
Edited by: user11979866 on 04-Nov-2010 08:48Hazel:
It would really depend on the sizes of the tables and the indexes available, but that is probably the way I would write it, at least as a first cut.
You could lose the distinct in the in sub-query since it is implied by the in itself, and Oracle will only return one row from the sub-query for each value of dept in A.
John -
Alternative/enhancement to union query?
Hello,
I have 2 sets of similar data which I am joining together with a union query.
Simplified E.g.
*Table A*
Name Dept
Ben 1
Amy 3
Ken 3
*Table B*
Name Dept
Jim 1
John 2
Sue 3
select Name, Dept
from table A
UNION
select Name, Dept
from table BWhat I would like to do is ONLY include data from the second part of the union query where it joins with some data from the first part of the union query.
E.g.
select Name, Dept
from table A
UNION
select Name, Dept
from table B
where Dept in (select distinct Dept from A)Therefore John that works in Dept 2 would not be included in the results.
Is there a better or more efficient way of doing this than my example using the subquery as part of the where clause?
Many thanks,
HazelHi, Hazel,
What you posted is as good as you can get without changing the tables.
You don't have to say DISTINCT in the IN-subquery:
where Dept in ( select Dept
from A
)will get the same results, perhaps a little faster. -
Customised sub-total via UNION query - how to exclude from totals?
Hi,
I have a client requirement that a couple of companies have their own sub-total in a report, a treatment which applies to no other companies in their group.
I have achieved this via a union all, but they also want a total of companies.
Is there anyway to emulate a Grand Total, other than another union query such that the double count is not double counted?
thanks for any ideas.
Robert.only solution which i can think of is to create another union request for the grand total.. this way you wont add up your sub totals twice..
-
How do I make a 'union' query?
Hi,
How do I make a union query in JDev? Something like this.
select 'x' from dual
union
select 'y' from dual;
to get a rowsetinfo for showing in a combobox control? Don't ask
me to create view in the database:-). It may not be practical for
all such adhoc queries.
--Gopal
nullHi
Sorry for that one. I didn't do my rtfm before asking that. There
is a constructor for QueryInfo which takes any sql statement.
--Gopal
Gopal (guest) wrote:
: Hi,
: How do I make a union query in JDev? Something like this.
: select 'x' from dual
: union
: select 'y' from dual;
: to get a rowsetinfo for showing in a combobox control? Don't
ask
: me to create view in the database:-). It may not be practical
for
: all such adhoc queries.
: --Gopal
null -
Create a Union query that automatically adds/contains new tables with a similar name
Dear All,
For a research project i am upscaling from an Access database to SQL server/ SQL azure since the database got far too large. Now i am quite well known with Access, but to be quite honest, I am a SQL rookey. So a lot to learn for me here.
what I need is a union query that automatically adds new research dumps to the query. All research dumps have a table name starting with TD_EXP (Table Dump _ Export). In Access VBA I simply made a loop that builds up the SQL statement, but i have no clue
how to do this within SQL Server...
So, I need the UNION Query to select * from TD_Exp_2012_06_06_15_48 UNON all the TD_Exp_XXXX_XX_XX_XX_XX that are added in the database,
Who could help me out please with a dynamic SQL statement.
Best regards Jurjenyou can use INFORMATION_SCHEMA.TABLES view for that
do like below
DECLARE @Query varchar(max)
SELECT @Query = STUFF((SELECT ' UNION ALL ' + 'SELECT * FROM ' + TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME LIKE 'TD_EXP%' FOR XML PATH('')),1,11,'')
SELECT @Query
Add one more condition as below if you want to exclude views from above
DECLARE @Query varchar(max)
SELECT @Query = STUFF((SELECT ' UNION ALL ' + 'SELECT * FROM ' + TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME LIKE 'TD_EXP%' AND TABLE_TYPE = 'BASE TABLE' FOR XML PATH('')),1,11,'')
SELECT @Query
Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs -
Trying to narrow down a UNIONed query
I've compared 2 tables using MINUS. There should have been no difference. Since there was, I used UNION to display the corresponding rows between both tables. Now, in my result set, I have to search through many rows that don't have correspondents to find rows that do.
Basically how do I narrow the UNION query down so that only the corresponding pair rows that have differences in their columns show up? I'm trying to use the primary key which is a combination of the first 5 columns. My query looks like this:
select
TRADE_DATE, ORDER_ROUTE_UID, ORDER_ENTRY_DATE, LEG_NBR, GROUP_SEQ_NBR,
AFFL_FIRM_GROUP_ID, REC_CREAT_DATE
from ors_firm_affl_hist@MSS_JOBS_HISTP01_LINK01.WORLD
union
select
TRADE_DATE, ORDER_ROUTE_UID, ORDER_ENTRY_DATE, LEG_NBR, GROUP_SEQ_NBR,
AFFL_FIRM_GROUP_ID, REC_CREAT_DATE
from ors_firm_affl_hist;
How can I use TRADE_DATE, ORDER_ROUTE_UID, ORDER_ENTRY_DATE, LEG_NBR, GROUP_SEQ_NBR in order to have the query display only the rows that have correspondents in the other table as opposed to rows that just aren't in either table?Not sure if this meets your requirements;
SQL> with t1 as (
select 'jon' first_name, 'smith' last_name, 'j' middle_init from dual union all
select 'tom', 'a', 'a' from dual union all
select 'bob', 's', 's' from dual union all
select 'Stan', 'm', 'l' from dual union all
select 'Kyle', 'b', 'r' from dual union all
select 'Kenny', 'm', 'r' from dual union all
select 'Eric', 'c', 'c' from dual),
t2 as (
select 'jon' first_name, 'smith' last_name, 'p' middle_init from dual union all
select 'tom', 'a', 'l' from dual union all
select 'bob', 's', 'j' from dual union all
select 'Stan', 'm', 'l' from dual union all
select 'Kyle', 'b', 'r' from dual union all
select 'Kenny', 'm', 'r' from dual union all
select 'Eric', 'c', 'c' from dual)
select 'T1' source, first_name, last_name, middle_init from t1
minus
select 'T1' source, first_name, last_name, middle_init from t2
union all
select 'T2' source, first_name, last_name, middle_init from t2
minus
select 'T2' source, first_name, last_name, middle_init from t1
order by 2,3,1
SO FIRST LAST_ M
T1 bob s s
T2 bob s j
T1 jon smith j
T2 jon smith p
T1 tom a a
T2 tom a l
6 rows selected. -
Including a SUM within a grouped UNION query
Hi - I have inherited a (SSRS) report comprising two queries with a UNION. There is a requirement to add one extra column which SUMS a total for each resource per month.
Grouping additional columns results in the following error:
Column 'dbo.MSP_EpmResource_UserView.ResourceName' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Any help appreciated.Your issue is that the subselect in your from block now contains a SUM but the other columns are not part of aggregate functions etc.
Even something simple like the following will give the same error:
CREATE TABLE #ForumExample (ColumnOne VARCHAR(3),ColumnTwo VARCHAR(3), ColumnThree VARCHAR(3), ColumnToBeSummed INT)
INSERT INTO #ForumExample
VALUES ('A','C','E',1),('A','C','E',2),('B','D','F',3),('B','D','F',4)
SELECT
ColumnOne,
SUM(ColumnToBeSummed)
FROM #ForumExample FE
DROP TABLE #ForumExample
To solve this, don't SUM the value in the subselect, just get each value for each row and then in the main SELECT block SUM the column and make sure to group by the summed result (not the column itself).
I havent had time to test this so I apologise if this doesn't work. -
PL/SQL Cartridge with Union Query
I have a pl/sql cartridge, with 3 select queries connected to each other by a "union". These queries basically generate a report from two tables. One of those queries is based on Table 1, and the other two are based on Table 2. What I need to accomplish is that I want to add a condition that restricts the outcome of the query (all three unions as a whole) based on a condition. Say, the condition is table1.param1 = '1'. Now, I'm getting confused with incorporating this condition in query 2 and query 3 which are based on table 2, and don't have the param1. However, both table1 and table 2 have param2 in common. I tried writing something like: (this is just a skeleton of my code)
SELECT param1, PARAM2, OTHER_PARAM
FROM table1
where param1 = '1'
union
select param2, param3, 0 other_param
from table2
where param2 in
(select param2
from table1
where param1 = '1')
union
select param2, param4, param5 other_param
from table2
where param2 in
(select param2
from table1
where param1 = '1');but this doesn't work. Can anyone help me with this query? any help is appreciated.I think it will help you guys better if I illustrate in more detail. Posting my code below. p1,p2,p3..etc are parameter names. Hope someone will be able to help now.
The original code, before adding the new condition is:
select p1_num,
p2_date,
sum(decode(p3,'50',p4,0)) b_amt,
sum(decode(p3,'10',p4,0)) r_amt,
sum(decode(p3,'20',p4,0)) d_amt,
sum(decode(p3,'40',p4,0)) l_amt,
0 pay_amt,
0 o_amt,
0 g_amt,
0 ot_amt
FROM table1 t1
where p1_num = passed_parameter -- Parameter passed to the cursor
AND to_char(p2_date, 'mmyyyy') = V_pdate -- V_pdate is a parameter passed to the procedure
group by p1_num, p2_date
UNION
select p1_num,
p6_date,
0,
0,
0,
0,
sum(decode(p7,'2', p8,0)) pay_amt,
0 o_amt,
0 g_amt,
0 ot_amt
from table2 t2
where p1_num = passed_parameter -- Parameter passed to the cursor
AND to_char(p6_date, 'mmyyyy') = V_pdate -- V_pdate is a parameter passed to the procedure
group by p1_num, p6_date
UNION
select p1_num,
p6_date,
0,
0,
0,
0,
0 pay_amt,
sum(decode(substr(p9,1,1),'1',p8,0)) oil_amt,
sum(decode(substr(p9,1,1),'2',p8,0)) gas_amt,
sum(decode(substr(p9,1,1),'5',p8,'3',p8,'4',p8,0)) ot_amt
from table2 t2
where ((p7 IS NULL) OR (p7 IN ('0','1','3','4')))
and p1_num = passed_parameter -- Parameter passed to the cursor
AND to_char(p6_date, 'mmyyyy') = V_pdate -- V_pdate is a parameter passed to the procedure
group by p1_num, p6_date;
I need to add a condition <b>p5 = '1'</b> to filter the results of this query. p5 is a from table1. I tried using inner join, as per Jane's suggestion, something like this:
select t1.p1_num,
t1.p2_date,
sum(decode(p3,'50',p4,0)) b_amt,
sum(decode(p3,'10',p4,0)) r_amt,
sum(decode(p3,'20',p4,0)) d_amt,
sum(decode(p3,'40',p4,0)) l_amt,
sum(decode(p7,'2', p8,0)) pay_amt,
sum(decode(substr(p9,1,1),'1',p8,0)) oil_amt,
sum(decode(substr(p9,1,1),'2',p8,0)) gas_amt,
sum(decode(substr(p9,1,1),'5',p8,'3',p8,'4',p8,0)) ot_amt
FROM table2 t2 inner join table1 t1
on t2.p1_num = t1.p1_num
WHERE
to_char(t1.p6_date,'mmyyyy') = V_pdate
and t1.p5 = '1'
and ((t2.p7 IS NULL) OR (t2.p7 IN ('0','1','3','4')))
group by t1.p1_num, t1.p2_date
order by t1.p1_num
Firstly, I get duplicates for some of the records, which I need to eliminate. Once I eliminate those, i'll know if my retrieved records are right (since right now its retrieving more than 1000 records!) -
OBIEE 10.1.3.3: We have a number of HR turnover reports that require calculations that use a formula of: #txns / average headcount. We need to run these reports for whatever beginning/ending dates the users enter. And, of course they need to be sliced and diced by any number of dimensions. I came up with a couple of different schemes to do this but keep running into roadblocks. It seems that a union is my best bet. here's the latest one generated:
SELECT saw_0, saw_1, saw_2, saw_3, saw_4, (saw_3 + saw_4)/2 saw_5,
(saw_2 / (saw_3 + saw_4)/2)*100 saw_6
FROM
((SELECT saw_0, saw_1, saw_2, saw_3, saw_4 FROM ... WHERE...)
UNION
(SELECT saw_0, saw_1, saw_2, saw_3, saw_4 FROM ... WHERE...)
UNION
(SELECT saw_0, saw_1, saw_2, saw_3, saw_4 FROM ... WHERE...)
)) t1 ORDER BY saw_0, saw_1
the first union select puts #txns in saw_2 and zeroes in saw_3 and saw_4
the second union select puts 1st date headcount in saw_3 and zeroes in saw_2 and saw_4
the third union select puts 2nd date headcount in saw_4, and zeroes in saw_2 and saw_3
The saw_6 calc won't work because the overall query needs to be aggregated. Here's the problem: When I add sum() clauses to the main query, it blows up because of no group by clause, and if I go into Advanced and try to add the group by and hit set sql, Answers cuts off the query and tells me there's no group by, even though it properly places the saw_0,saw_1 fields in the group by box below. Seems like a bug in Answers, because when I take the SQL I altered and run it from the Admin SQL tool, it returns the result I wanted.
Any ideas? If you got this far, thanks for reading all of this...
GregI am using very similar query with union all and sum () to get approval ratings between any given dates, but I did not explicitly specify groupby and it works. I am using 7.8.4.
Maybe you are looking for
-
bt gave me information that i acted upon in good faith when it turned out to be wrong imformation they tried to hide behind contract law if you ring up you get told misleading imformation they wont comfirm by email if you ask the questions by the cha
-
Business Objects in vmware cluster very slow
Post Author: aboorkuma CA Forum: Administration Hi I recently move the BO From standalone server to Cluster in vmwrae users are facing problem when accessing the reports , some times page cannot displayed or timeout coming now it is very very slow wh
-
Biller Direct Customer's Payment Advise
Hi, I am having an issue with Biller Direct (BD). The customer creates the payment advise in BD (starting with 09) and it is available in SAP with FBE3 and in BD showing the invoices to be paid and the amounts. It also shows any credits that the cust
-
Hi Gurus, I have created Purchase order output usind Smartform. As there is no standard printing program, I have created z_program for printing, which is working well. But when I want to see preview using print preview button, there is nothing displa
-
Hi, I'm building a component which serves as mediator between 3rd-party API and the rest of my app. Basically, my problem is that I need to capture and handle some events sent by the API, do some work, and then trigger an event which will be used by