Adding count from two select statements
Hi,
How to add counts from two select statements in a single SQL statement.
For ex: I have
SELECT COUNT(DISTINCT COL1) FROM table1
and
SELECT COUNT(DISTINCT COL2) FROM table2.
I want to add the counts from these two sqls in a single select query. How to do this.
Thanks & Regards,
Sunil.
select ((SELECT COUNT(DISTINCT COL1) FROM table1) + (SELECT COUNT(DISTINCT COL2) FROM table2)) as "total" from dual;
regards,
Similar Messages
-
Count the number of rows resulting from a select statement
Hi,
Is there any way of counting the number of rows resulting from a select statement. i.e I have a select distinct statement and I then want to perform an IF statement on the number of rows resulting from the select statement.
Any help appreciated
Thanks
GaryDeclare
var1 number;
Begin
select count(distinct column_name) into
var1 from table_name;
If var1 > x Then
End IF;
End;
Hope I understood the problem correctly
null -
Combine two select statements in one SQL statements
I have the following two queries that I need to combine into one query, where it updates a single row at the same time.
SELECT count(*) FROM database.USAGE WHERE SERVICE_TYPE = 'C' AND ACCOUNT = "4837"
SELECT sum(minutes) FROM database.USAGE WHERE SERVICE_TYPE = 'DA' AND ACCOUNT = "4837"
I want to insert the values of each select statement into two columns of the same row, as well as insert the account number from the select statement.
After the query has been executed, the database row will look like this:
ACCOUNT COUNT SUM
4837 354 1039202
I am looking for suggestions on how to:
- either combine the two into one query
- simply update each column with the value from each query by updating the row with the account value
I am a SQL newbie - so I appreciate any assistance.
Thanks,
TonyHi, Tony,
When you're talking about changing the data in tables, "INSERT" means to add a new row, and you'll cause a lot of confusion if you use it to mean something else. So don't say
"I want to insert the values of each select statement into two columns..."; use some other word, like:
"I want to put the values of each select statement into two columns ..."
If you happened to know that those two numbers were 354 and 1039202, you might say:
UPDATE table_x
SET a_count = 354
, a_sum = 1039202
WHERE account = 4837;But you don't know the numbers; you want to have the query figure out what they are.
In most places where you can use a literal (like 354 or 1039202), you can also use a scalar sub-query, a SELECT statement, enclosed in parentheses, that produces one column and (at most) one row.
In your case, you can say:
UPDATE table_x
SET a_count = (SELECT count(*) FROM database.USAGE WHERE SERVICE_TYPE = 'C' AND ACCOUNT = 4837)
, a_sum = (SELECT sum(minutes) FROM database.USAGE WHERE SERVICE_TYPE = 'DA' AND ACCOUNT = 4837
WHERE account = 4837;or, to make it more readable:
UPDATE table_x
SET a_count =
( SELECT count (*)
FROM database.USAGE
WHERE SERVICE_TYPE = 'C'
AND ACCOUNT = 4837
, a_sum =
( SELECT sum (minutes)
FROM database.USAGE
WHERE SERVICE_TYPE = 'DA'
AND ACCOUNT = 4837
WHERE account = 4837;By the way, why are you using double-quotes around 4837? If it's a string, enclose it in single quotes. If it's a number (which I'm assuming in my code), don't enclose it in anything.
WARNING: scalar sub-queries are somewhat like duct tape: they're extremely useful in certain places, and those places account for about 1% of their use. The other 99% of the time, there's a better way to do things, though the better way may require more expertise. -
How to pass an array to a function from a SELECT statement
Hi all. I have a problem with passing an array to a function directly from a SELECT statement.
Here is what I want. If I have a function
function AAA(arrayVar <ArrayType>) return number;
I want to be able to call this function this way
select AAA((2,3,4))
from dual
or this way
select AAA((10,12))
from dual
In other words I want to be able to pass an arbitrary number of numbers to the function. And I want this to work in a SELECT statement.
Does anyone have any ideas how to implement this? What <ArrayType> should I use?(I've read about VARRAY, nested tables in the Oracle documentation but as far as I've understood these array types are meant to be used within PL/SQL blocks).
I found only this http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:208012348074 through Google but it didn't help me.
Thank you in advance.> What <ArrayType> should I use?
SQL data types - as 3360 showed above. You cannot use PL/SQL structures and user types in the SQL Engine.
You can however use all SQL structures and types in PL/SQL.
Arrays in SQL is created as collection type - basic o-o. The collection type (or class) serve as a container for instantiated objects or scalar type.
This is covered in detail in [url http://download-uk.oracle.com/docs/cd/B19306_01/appdev.102/b14260/toc.htm]
Oracle® Database Application Developer's Guide - Object-Relational Features -
Rerieve Duplicate Rows from a SELECT statement
Hi, I want to see all the duplicate rows from my SELECT statement. Looks like Oracle by default suppresses the duplicate rows. Here is my SQL statement.
I like to see all the 5 rows. Please help.
select a.partid, a.pdesc
from product a
where a.partid in ('10-30000-4',
'10-30000-4',
'10-30000-4',
'10-30000-4',
'10-30000-5')Looks like Oracle by default suppresses the duplicate rowsSure no, if you have duplicate rows, Oracle will show you the dup rows.
Please, paste your data and the query result.
And this is no because you'll put multiple time the same condition that Oracle will show you multiple time the same row (in case of non-duplicate).
Nicolas. -
Calculating count from two fact tables
Hi Guys,
My requirement,
i have two fact table F1, F2 connected with a D1 dimension table, all table connected with a id column
F1 ---------D1------------F2
n 1 1 n
i want to find out the distinct count from Fact F1 where the value also present in F2( ie. F1.id= F2.id condition).
this measure usefull through out my project so i want create a logical column, how to create it.
I tried this way:
i Created two fact table in to one fact table by adding logical source, and created a logical column from existing logical source where F1.id=D1.id and D1.id=F2.Id but it is wrong
Can any suggestion for solve my problem.
Thanks in advance!!!Hi,
You can create an opaque view in physical layer and wrire a sql like
Select f1.id,count(*) from f1,f2 where f1.id=f2.id group by f1.id.Join this through id with dimesnion and add this fact table in LTS of your fact and use count(*) in report.
Regards,
Sandeep -
How to processing the results from the select statement in SQL query?
Hi
This might be too simple, but my knowledge of the SQL is very limited...
I have table where I do have details from calls (Lync QoE).
I can take all calls from the table, but I would like to count the concurrent calls on the table. This is how I got it work on the Excel to work (but I would like to do that on the SQL statement to get it more dynamic use):
Table have these line and this is what I get out from the Select):
[callid],[start],[end]
1ABC,1.1.2014 01:00:15, 1.1.2014 01:01:00
5DEF,1.1.2014 01:00:45, 1.1.2014 01:05:00
FDE2,1.1.2014 01:03:15, 1.1.2014 01:04:00
KDJ8,1.1.2014 01:04:15, 1.1.2014 01:06:00
FDJ8,2.1.2014 01:04:15, 2.1.2014 01:06:00
KDSE,3.1.2014 01:04:15, 3.1.2014 01:06:00
The information I would like to get, is what is the maximum amount of the concurrent calls per day.
On the excel I basically count line by line how many concurrent calls each line have had, and then pickup the highest one. On above example the calls 5DEF, FDE2 and FDE2 have been active at the same time which gives 3 for the first day.
The table is ordered by the start. So let say the code is on the third line (FDE2). I need to count calls from before which end time is after the start time (of FDE2), but also I need to count calls after (FDE2) which are started before the current
call has ended.
PetriUnfortunately your post is off topic as it's not specific to SQL Server Samples and Community Projects.
This is a standard response I’ve written in advance to help the many people who post their question in this forum in error, but please don’t ignore it. The links I provide below will help you determine the right forum to ask your question in.
For technical issues with Microsoft products that you would run into as an end user, please visit the Microsoft Answers forum ( http://answers.microsoft.com ) which has sections for Windows, Hotmail,
Office, IE, and other products.
For Technical issues with Microsoft products that you might have as an IT professional (like technical installation issues, or other IT issues), please head to the TechNet Discussion forums at http://social.technet.microsoft.com/forums/en-us, and
search for your product name.
For issues with products you might have as a Developer (like how to talk to APIs, what version of software do what, or other developer issues), please head to the MSDN discussion forums at http://social.msdn.microsoft.com/forums/en-us, and
search for your product or issue.
If you’re asking a question particularly about one of the Microsoft Dynamics products, a great place to start is here: http://community.dynamics.com/
If you think your issue is related to SQL Server Samples and Community Projects and I've flagged it as Off-topic, I apologise. Please repost your question and include as much detail as possible about your problem so that someone can assist you further.
If you really have no idea where to post your question please visit the Where is the forum for…? forum http://social.msdn.microsoft.com/forums/en-us/whatforum/
When you see answers and helpful posts, please click Vote As Helpful,
Propose As Answer, and/or Mark As Answer
Jeff Wharton
MSysDev (C.Sturt), MDbDsgnMgt (C.Sturt), MCT, MCPD, MCSD, MCSA, MCITP, MCDBA
Blog: Mr. Wharty's Ramblings
Twitter: @Mr_Wharty
MC ID:
Microsoft Transcript -
Count(*) function in select statement having group by condition
Hi
I would like to use count(*) in select statement having group by clause. say for example there is a state with a number of cities listed. I would like to get the count of cities for each state.
the sql stement is grouped by state and it is joined with 5 more tables.
Thanks
ps: ignore the previous postAssuming there is one record per city per state, then
SELECT state,count(*)
FROM state_tbl
GROUP BY stateWill get one record per state with the number of cities in each state. If you want to join that result set to other tables you need to either create a view with that statement or use an in-line view viz.
SELECT c.cust_name,c.state,s.num_cities
FROM customers c,
(SELECT state,count(*) num_cities
FROM state_tbl
GROUP BY state) s
WHERE c.state = s.stateTTFN
John -
Getting DISTINCT count from two different columns
Hi all,
I have following query which gives currency code from two different tables. I would like to get the distinct count of currency codes from these two different columns.
SELECT eb.person_seq_id, eb.bonus_amount, eb.currency_cd, ed.currency_cd_host
FROM fr_emp_bonuses eb, fr_emp_details ed, fr_periods p
WHERE eb.person_seq_id = ed.person_seq_id AND ed.period_seq_id = eb.period_seq_id
AND ed.period_seq_id = p.period_seq_id AND p.period_status = 'CURRENT'
AND eb.bonus_amount >= 0 AND eb.person_seq_id = 3525125;
This query gives following result
3525125 240000 USD INR
3525125 0 USD INR
3525125 60000 USD INR
3525125 50000 USD INR
There are two distinct currency codes (USD, INR) and total amount is 350000. So I am looking for a query to give me the following result
3525125 350000 2
Thanks in advanceHi,
Here's one way:
WITH original_query AS
SELECT eb.person_seq_id
, eb.bonus_amount
, eb.currency_cd
, ed.currency_cd_host
FROM fr_emp_bonuses eb
, fr_emp_details ed
, fr_periods p
WHERE eb.person_seq_id = ed.person_seq_id
AND ed.period_seq_id = eb.period_seq_id
AND ed.period_seq_id = p.period_seq_id
AND p.period_status = 'CURRENT'
AND eb.bonus_amount >= 0
AND eb.person_seq_id = 3525125
, unpivoted_data AS
SELECT person_seq_id
, bonus_amount
, currency_cd
FROM original_query
UNION ALL
SELECT person_seq_id
, 0 AS bonus_amount
, currency_cd_host AS currency_cd
FROM original_query
SELECT person_seq_id
, SUM (bonus_amount) AS total_bonus_amount
, COUNT (DISTINCT currency_cd) AS distinct_currency_cds
FROM unpivoted_data
GROUP BY person_seq_id
;There may be a shorter, more efficient way to get the same results, but without knowing more about your tables, I can't tell.
The tricky thing is getting two columns (currency_cd and currencuy_cd_host in this case) counted together. You can't simply say
COUNT (DISTINCT eb.currency_cd) +
COUNT (DISTINCT ed.currency_code_host)That happens to get the correct result with the sample data you posted, but what if you had data like thEe following?
currency_cd currency_cd_host
INR USD
USD INRHere, the count of distinct currency_cds is 2, and the count of distinct currency_cd_hsots is also 2. Does that mean the grand total is 2 + 2 = 4? No, the 2 codes in one column arte the same 2 codes as in the other column. We need to get both currency_cd and currency_cd_hsot into the same column, and then do COUNT (DISTINCT ...) on that combined column. A UNION, as shown above, will certainly do that, starting with your query as you posted it. The query you posted isn't necessarily the best frist step towards this result, however, so there may be a much better approach, depending on your tables.
Edited by: Frank Kulash on Feb 1, 2012 6:21 PM
Here's a slightly shorter, and probably more efficient way to get the same results:
WITH cntr AS
SELECT LEVEL AS n
FROM dual
CONNECT BY LEVEL <= 2
SELECT eb.person_seq_id
, SUM (eb.bonus_amount) AS total-amount
, COUNT ( DISTINCT CASE
WHEN c.n = 1
THEN eb.currency_cd
ELSE ed.currency_cd_host
END
) AS distinct_currency_cds
FROM fr_emp_bonuses eb
, fr_emp_details ed
, fr_periods p
, cntr c
WHERE eb.person_seq_id = ed.person_seq_id
AND ed.period_seq_id = eb.period_seq_id
AND ed.period_seq_id = p.period_seq_id
AND p.period_status = 'CURRENT'
AND eb.bonus_amount >= 0
AND eb.person_seq_i = 3525125
-- NOTE: no join condition involving c; we really do want a cross-join
GROUP BY eb.person_seq_id
; -
How can I call a Page Process from the Select statement for Report Page
I'm able to call a javascript using the below:
img src="#IMAGE_PREFIX#add2.gif" border="0" alt="Icon 4" onClick="javascript:add_connect1('||CPORT.ID||')"
But Now,
I'd like to accomplish (2) New things:
1. instead of using,....... onClick="javascript:add_connect1,
I'd like to call a Page Process, onClick=
2. I'd like to be able to call two different processes onClick.
a. onClick="javascript:passBack('||ID||')"
b. onClick= <Please see my question #1 above>
Can someone please help me with the syntax for this,
If indeed it can even be done?
Thanks- GaryGreg.
It seems that my situation is the one you describe in you second paragraph, where you mention:
you could then add the ID column value as a parameter to the javascript functionBut,
I do not know how to reference the variable in my javascript nor how to use it in my on-demand process.
If you can hellp me past this last little bump, then I think I will be able to use these skills in Sooo many different areas of my design.
Here's what I've got so far:
A. In the select statement I identify the javascript as:
onClick="javascript:connect_port('<font color=blue>''||ID||''</font>')";
B. In my javascript I have this:
<script language="JavaScript" type="text/javascript">
function connect_port(ID)
var get = new htmldb_Get(null,$x('pFlowId').value,'APPLICATION_PROCESS=CONNECT_PORT',0);
gReturn = get.get();
get = null;
</script>
C. In my on demand function I have this:
BEGIN
INSERT INTO CCONNECTIONS_B
BLDG_ID,CLST_ID,PORT_ID,STRAND_ID
) VALUES
:P2004_BLDG_ID,:P2004_CLST_ID,:P2004_PORT_ID,:P2004_STRAND_ID1
END;
You can see that I dont know how to use the value for 'ID' in either the javascript or the On-Process function.
If you can help me out with this one, Then I can imitate it for the rest.
-Gary
Edited by: garyNboston on Apr 3, 2009 6:44 AM
Edited by: garyNboston on Apr 3, 2009 6:44 AM
Edited by: garyNboston on Apr 3, 2009 6:45 AM
Edited by: garyNboston on Apr 3, 2009 6:47 AM -
Querying many tables at once from a select statement for specific values
Hi all,
I'm very new to PL/SQL and have a daunting task ahead of me. I'm pretty sure our database normalization scheme is all out of whack, which I dont have the experience to fix yet, but this is the task ahead of me without getting to change or fix our structure:
in the universe has 1000+ tables.
need--> Some of those tables have fields that contain a value that has to be changed.
The only thing I have to go on is the column name will contain 'EMP'... but there is no specific naming convention for the column names.
When I search on:
select * from all_tab_columns where column_name like UPPER('%EMP%')
It returns 750 rows. (So 750 rows = 750 columns in 500 different tables (some tables have 2 or more columns in it))
tables names are random (table1, table2, etc).
columns names are random with EMP in it (column1,column2,etc).
I have 75 possible field values that I need to check each of those 750 columns for.
Maybe this is too messy, but I'm looking at subqueries, joins, arrays, cursors, etc, anything to minimize the amount of work I have to do.
I think this is too much to do a join with, but that seems to be what all the documentation is pointing me to.
can you point me to a simple example of what i could
write?
the logic i see it would be
run the select statement to grab the column names that meet EMP.
one at a time, search each column in the corresponding table for the 75 values.
return the results of rows for each column/table that meet one of the 75 unique values.
I'll have to also update each of the 75 values to (used to be values 1, 2, 3 ... to new values X1, X2, X3, etc.)
Any help at all would be very helpful,
aspiring pl/sql programmer but having a rough time of itI think you're looking to do something like the following pseudocode:
BEGIN
FOR tblrec IN (SELECT table_name, column_name
FROM all_tab_columns
WHERE column_name LIKE '%EMP%')
LOOP
FOR rec IN (SELECT ROWID
FROM tblrec.table_name
WHERE REGEXP_LIKE(tblrec.column_name, '(expr1|expr2|...)')
LOOP
DBMS_OUTPUT.PUT_LINE(
'Found expression on ROWID ' || rec.rowid
|| ' in column ' || tblrec.column_name
|| ' on table ' || tblrec.table_name);
END LOOP;
END LOOP;
END; -
How do I return the results of two SELECT statements in to one result?
I want to do this without using UNION.
Here's an example of what I'm trying to do:
I have a table called COUNTRY with the following columns:
COUNTRY
COUNTRY_CODE
DATE_VISITED_LAST
POPULATIONI have another table called STATE_COUNTY with the following columns:
STATE_COUNTY
COUNTRY_CODE
STATE_COUNTY_CODE
DATE_LAST_VISITED
POPULATIONI have a third table called TOWN with the following columns:
TOWN
COUNTRY_CODE
STATE_COUNTY_CODE
TOWN_CODE
DATE_LAST_VISITED
POPULATIONNow through the interface I have, a user will supply a country code. I need a SELECT statement that will return a table with the following result set:
The COUNTRY_CODE entered including the DATE_LAST_VISITED and POPULATION for this country
------> All the associated STATE_COUNTY's belonging to this country along with the DATE_LAST_VISITED and POPULATION for each STATE_COUNTY_CODE.
-------------> All the associated TOWN_CODE's belonging to this state_county and country along with the DATE_LAST_VISITED and population for each TOWN.
So the table will have 9 columns:
COUNTRY
DATE_LAST_VISITED_COUNTRY
POPULATION_COUNTRY
STATE_COUNTY
DATE_LAST_VISITED_STATE_COUNTY
POPULATION_COUNTY
TOWN
DATE_LAST_VISITED_TOWN
POPULATION_TOWNAny ideas how this can be done?
Thanks.Hi guys,
Would it be ok to do it like this (with a join):
SELECT
c.country_code,
c.date_last_visited AS DATE_LAST_VISITED_COUNTRY,
c.population AS POPULATION_COUNTRY,
s.state_county_code,
s.date_last_visited AS DATE_LAST_VISITED_STATE_COUNTY,
s.population AS POPULATION_COUNTY,
t.town_code,
t.date_last_visited AS DATE_LAST_VISITED_TOWN,
t.population POPULATION_TOWN,
FROM
country c
LEFT OUTER JOIN state_county s ON s.country_code = c.country_code
LEFT OUTER JOIN town t ON t.country_code = s.country_code
AND t.state_county_code = s.state_county_codeThe results required would be something like:
Country_Code DATE_LAST_VISITED_COUNTRY POPULATION_COUNTRY STATE_COUNTY_CODE DATE_LAST_VISITED_STATE_COUNTY POPULATION_COUNTY TOWN_CODE DATE_LAST_VISITED_TOWN POPULATION_TOWN
UK 14-JAN-09 56,00000 London 18-JUL-99 23,0000 Ascot 30-JUN-89 12,000
Brixton 28-JAN-92 4,684
Birmingham 12-SEP-09 55,678 Solihull 12-OCT-81 6.768 Does this make sense?
Thanks!
Edited by: Sastry on Nov 2, 2009 2:04 AM -
Fetching a value from a select statement inside select clause
hello all,
I have a problem executing a procedure it gives me a runtime error, what am doing is i have multiple select statement inside a select clause. am using the entire select statement for a ref cursor. when running the query seperately am able to get the records but it's not getting compiled.
here is the piece of code which am working with
create or replace procedure cosd_telecommute_procedure
(p_from_date in date,
p_to_date in date,
p_rset in out sys_refcursor)
as
p_str varchar2(10000);
begin
p_str := 'select personnum, '||
'fullname, '||
'personid, '||
'hours, '||
'applydtm, '||
'paycodeid, '||
'laborlev2nm, '||
'laborlev3nm, '||
'laborlev2dsc, '||
'adjdate, '||
'timeshtitemtypeid, '||
'(select max(eff_dt) from cosd_telecommute_info_tbl '||
'where emplid = cosd_vp_telecommute.personnum and '||
'eff_dt between ''01-aug-2005'' and ''30-aug-2005'') thisyreffdt, '||
'(select elig_config7 from cosd_telecommute_info_tbl '||
'where emplid = cosd_vp_telecommute.personnum and '||
'eff_dt = (select max(eff_dt) from cosd_telecommute_info_tbl '||
'where emplid = cosd_vp_telecommute.personnum and '||
'eff_dt between ''01-aug-2005'' and ''30-aug-2005'')) thisyrmiles,'||
'(select max(eff_dt) from cosd_telecommute_info_tbl '||
'where emplid = cosd_vp_telecommute.personnum and '||
'eff_dt between trunc(p_from_date) and trunc(p_to_date)) fiscalyreffdt, '||
'(select elig_config7 from cosd_telecommute_info_tbl '||
'where emplid = cosd_vp_telecommute.personnum and '||
'eff_dt = (select max(eff_dt) from cosd_telecommute_info_tbl '||
'where emplid = cosd_vp_telecommute.personnum and '||
'eff_dt between trunc(p_from_date) and trunc(p_to_date))) fiscalyrmiles '||
'from cosd_vp_telecommute '||
'where trunc(applydtm) '||
'between p_from_date and p_to_date '||
'and personnum = ''029791''';
open p_rset for p_str;
end cosd_telecommute_procedure;
and here is the piece of error am getting
ERROR at line 1:
ORA-00904: invalid column name
ORA-06512: at "TKCSOWNER.COSD_TELECOMMUTE_PROCEDURE", line 40
ORA-06512: at line 5Did you run the query in SQL plus? Check whether all the column are valid in your database. Below is the query which i got from your procedure just run and check it out. It is really hard for us to tell you the problem without knowing the table structure
select personnum, fullname, personid, hours, applydtm, paycodeid, laborlev2nm, laborlev3nm,
laborlev2dsc, adjdate, timeshtitemtypeid,
(select max(eff_dt) from cosd_telecommute_info_tbl
where emplid = cosd_vp_telecommute.personnum
and eff_dt between '01-aug-2005' and '30-aug-2005') thisyreffdt,
(select elig_config7 from cosd_telecommute_info_tbl where emplid = cosd_vp_telecommute.personnum
and eff_dt = (select max(eff_dt)
from cosd_telecommute_info_tbl
where emplid = cosd_vp_telecommute.personnum
and eff_dt between '01-aug-2005' and '30-aug-2005'
) thisyrmiles,
(select max(eff_dt)
from cosd_telecommute_info_tbl
where emplid = cosd_vp_telecommute.personnum
and eff_dt between trunc(p_from_date) and trunc(p_to_date)
) fiscalyreffdt,
(select elig_config7 from cosd_telecommute_info_tbl where emplid = cosd_vp_telecommute.personnum
and eff_dt = (select max(eff_dt)
from cosd_telecommute_info_tbl
where emplid = cosd_vp_telecommute.personnum
and eff_dt between trunc(p_from_date) and trunc(p_to_date)
) fiscalyrmiles
from cosd_vp_telecommute
where trunc(applydtm) between p_from_date and p_to_date
and personnum = '029791' -
Urgent Q-adding elements from two data sets
How to add two fields from two data sets. in RTF template
the fields have same names too.BIPuser wrote:
If you are grouping within one data set, then the current-group will only work for an element within that group. For the second one, try to use the absolute path or use as many of '../' to get up as many levels from where you are.
Thanks!I have defined two different groups.
I need to add the elements from those two diffrent groups. -
Join same table 3 times, count from two other tables
Hi all!
I have 3 tables
RECORDS
Id, Record_Id
ITEMS
Id, Record_Id
ARTICLES
Id, Record_Id
I need to join RECORDS table 3 times R1,R2,R3 and get count of items R2 and R3 have and count articles that R3 has.
R2 must have ITEMS and R3 must have items, R3 may have articles. R1 may have multiple children and R2 may have multiple children.
Solution I'm using is following, but distinct makes it slow...
select r1 as ParentRecordId,count(distinct i1) as Volumes,count(distinct i2) as Numbers, count(distinct a1) as Articles
from
select r1.id as r1,i1.id as i1,i2.id as i2,a.id as a1
from records r1 inner join records r2 on r1.id=r2.record_id
inner join records r3 on r2.id=r3.record_id
inner join items i1 on r2.id=i1.record_id
inner join items i2 on r3.id=i2.record_id
left join articles a on a.record_id=r3.id
) as sel
group by r1
order by 1
Regards
MeelisPlease post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions and formatting rules. Temporal data should
use ISO-8601 formats. Code should be in Standard SQL as much as possible and not local dialect.
This is minimal polite behavior on SQL forums. And thanks for no sample, too!
>> I have 3 tables <<
No, you have three identical decks of 1950's punch cards written in bad SQL.
There is no such thing as a generic, universal “id” in RDBMS. It has to be the identifier of something particular.
Magical columns appear in your query.
There is no such concept as “child' and “parent” in RDBMS. That was network and hierarchical databases. We have referenced and referencing tables.
We do not use column positions in the ORDER BY cause; any change in the query used in the cursor will screw up everything.
Would you like to try again?
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL
Maybe you are looking for
-
hi, i buy new laptop dell inspiron 5521r core i7 3517u 1.9-2.40 GHz with built in OS windows 8 single language it is working good, but when i update to windows 8.1 single language, after all long time update it becomes restarting, then when i was log
-
As I said, I upgraded my MacBook Pro (2011) from Lion to Mountain Lion last night. This morning I couldn't get it to boot up at all. The beach ball just spun and spun. Now I can get it to my desktop and can see my wallpaper, but it takes another F
-
Data Associtions not enabling while i am trying to do data mapping with data Associtions in BPM studio what is the reson?
-
Error in destination tab gateway cockpit SMP 3.0 SP05
Hi Experts, I created a destination in destination's tab and it was working fine. But now, I'm facing error when trying to connect to the destination. I have attached the screen shots . I restarted the SMP server and got the error as shown in the ima
-
Issue Regarding ALV List Report
Hi, I have prepared a ALV List report. I have made use of <b>REUSE_ALV_LIST_DISPLAY</b>. I have put a <b>check box</b> in the output at the begining of every Record. Now what i want is to put a <b>SELECT ALL</b> & <b>DESELECT ALL Buttons</b> on Appli