Prioritizing distinct counts from aggregate table
I am a relatively new developer with limited PL/SQL experience trying to modify an existing query that extracts counts from an aggregate table. What I need to do is set it up so that it only counts the record once based on it's priority. This is currently set up in a DECODE Statement counting only totals (not distinct nor prioritized). What Im trying to accomplish would be something like this:
If Service 'A' exists count it and stop. If more than one Service A exists count only once.
If Service 'A' does not exist then check if 'B' exist, if 'B' exists count it and stop. If more than one Service B exists count only once.
If Service 'B' does not exist then check if 'C' exist, if 'C' exists count it and stop. If more than one Service C exists count only once. etc.
It may be possible to have multiple services in a given category and if so should be counted only once.
Here is a snipit of the existing code....
COUNT
(DECODE (service_id,
1, program_enrollment_id
) basic_readjustment,
COUNT
(DECODE (service_id,
2, program_enrollment_id
) occupation_skills,
COUNT (DECODE (service_id,
3, program_enrollment_id
) on_the_job,
COUNT
(DECODE (service_id,
4, program_enrollment_id
) placement_assist
Any help you can give would be appreciated!
Mark
Yes, although based on your last post, it is not quite a simple as my example. Your original query as posted will count each occurence of each service_id whether there is one or many for a group. The DISTINCT on the innermost query, against wia_bas_mv, will remove duplicates for a particular service_id, but would leave multiple records it there were different service_ids for the same group.
The trick is to to get only one record for each group, and make sure that that record is the "highest" priority record. Since your priority order does not match the sort order of the service_ids, you need to add an extra DECODE to get them to "sort" in the right order. Assuming that I have done the service_id mapping correctly, this should be close to what you are looking for:
SELECT region_id, region_name, officegroupname, officegroupid,
SUM(basic_readjustment) basic_readjustment,
SUM(occupation_skills) occupation_skills,
SUM(on_the_job) on_the_job, SUM(placement_assist) placement_assist,
SUM(other) other,
SUM(basic_readjustment + occupation_skills + on_the_job +
placement_assist + other) total
FROM (SELECT officegroupname, officegroupid, region_id, region_name,
SUM(DECODE(service_id, 'C', 1, 0)) basic_readjustment,
SUM(DECODE(service_id, 'A', 1, 0)) occupation_skills,
SUM(DECODE(service_id, 'B', 1, 0)) on_the_job,
SUM(DECODE(service_id, 'D', 1, 0)) placement_assist,
SUM(DECODE(service_id, 'E', 1, 0) other
FROM (SELECT program_enrollment_id, officegroupname,
officegroupid, region_id, region_name,
MIN(DECODE(service_id, 368, 'A', 369, 'B', 144, 'C',
114, 'D', 'E')) service_id
FROM wia_base_mv
WHERE region_id < 13 AND
program_value = 'VAL04_TAA' AND
actual_completion_date IS NULL
GROUP BY program_enrollment_id, officegroupname,
officegroupid, region_id, region_name)
GROUP BY officegroupname, officegroupid, region_id, region_name
UNION ALL
SELECT r.region_id, r.region_name, og.officegroupname,
og.officegroupid, 0 basic_readjustment, 0 occupation_skills,
0 on_the_job, 0 placement_assist, 0 other
FROM officegroup og, regions r, office_data od
WHERE r.region_id = od.region_id AND
og.officeid = od.office_id)
GROUP BY region_id, region_name, officegroupname, officegroupid
ORDER BY region_id HTH
John
Similar Messages
-
CE function to get distinct values from Column table
Hi All,
Could you please let me know the appropriate CE function to get the distinct values from column table.
IT_WORK = SELECT DISTINCT AUFNR FROM :IT_WO_DETAILS;
Thank you.Hi,
If you have 10g, you can use Model( with model performance is better than connect by )
Solution
========================================================================
WITH t AS
(SELECT '0989.726332, 1234.567432, 3453.736379, 3453.736379, 0989.726332, 3453.736379, 1234.567432, 1234.567432, 0989.726332'
txt
FROM DUAL)
SELECT DISTINCT TRIM(CHAINE)
FROM T
MODEL
RETURN UPDATED ROWS
DIMENSION BY (0 POSITION)
MEASURES (CAST( ' ' AS VARCHAR2(50)) AS CHAINE ,txt ,LENGTH(REGEXP_REPLACE(txt,'[^,]+',''))+1 NB_MOT)
RULES
(CHAINE[FOR POSITION FROM 1 TO NVL(NB_MOT[0],1) INCREMENT 1] =
CASE WHEN NB_MOT[0] IS NULL THEN TXT[0] ELSE REGEXP_SUBSTR(txt[0],'[^,]+',1,CV(POSITION)) END );
=========================================================================
Demo
=======================================================================
SQL> WITH t AS
2 (SELECT '0989.726332, 1234.567432, 3453.736379, 3453.736379, 0989.726332, 3453.736379, 123
4.567432, 1234.567432, 0989.726332'
3 txt
4 FROM DUAL)
5 SELECT DISTINCT TRIM(CHAINE)
6 FROM T
7 MODEL
8 RETURN UPDATED ROWS
9 DIMENSION BY (0 POSITION)
10 MEASURES (CAST( ' ' AS VARCHAR2(50)) AS CHAINE ,txt ,LENGTH(REGEXP_REPLACE(txt,'[^,]+',''))+1 NB_MOT)
11 RULES
12 (CHAINE[FOR POSITION FROM 1 TO NVL(NB_MOT[0],1) INCREMENT 1] =
13 CASE WHEN NB_MOT[0] IS NULL THEN TXT[0] ELSE REGEXP_SUBSTR(txt[0],'[^,]+',1,CV(POSITION)) END );
TRIM(CHAINE)
3453.736379
1234.567432
0989.726332
SQL>
======================================================================== -
Need of SQL query in selecting distinct values from two tables
hi,
I need a query for selecting distinct values from two tables with one condition.
for eg:
there are two tables a & b.
in table a there are values like age,sex,name,empno and in table b valuses are such as age,salary,DOJ,empno.
here what i need is with the help of empno as unique field,i need to select distinct values from two tables (ie) except age.
can anybody please help me.
Thanks in advance,
RatheeshNot sure what you mean either, but perhaps this will start a dialog:
SELECT DISTINCT a.empno,
a.name,
a.sex,
b.salary,
b.doj
FROM a,
b
WHERE a.empno = b.empno;Greg -
Collumn Count from Database Table
Hello,
I wan't to get a Collumn Count from a Table in my Database, but I don't know how to do that.
I use a ResultSet, and if i press ctrl + spacebar in NetBeans I get a list of all kind of things I can get out of the result set but I can't find CollumnCount anywhere.
I thought I could use a try catch statement like this:
try
for(i=1; i<999; i++)
myResultSet().getString(i);
catch( Exception e )
AantalKolommen = i--;
But everytime I get an Exception over Invalid Crursor State and "i" keeps standing on 1.
Does anybody know a way to find out how to get a collumns count????To retrieve the columns for a table use
http://java.sun.com/j2se/1.4.2/docs/api/java/sql/DatabaseMetaData.html#getColumns(java.lang.String,%20java.lang.String,%20java.lang.String,%20java.lang.String)
To get the columns for your result set use
http://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSetMetaData.html#getColumnCount()
To get the ResultSetMetaData use
http://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.html#getMetaData() -
Display distinct rows from Oracle table without using "DISTINCT" keyword.
How to retrieve distinct rows from oracle table without using 'DISTINCT' keyword in SQL?
Thanks in advance.
MihirWelcome to the forum.
Besides GROUP BY you can use UNIQUE instead of DISTINCT as well, but that's probably not wanted here ;) , and the ROW_NUMBER() analytic:
SQL> create table t as
2 select 1 col1 from dual union all
3 select 1 from dual union all
4 select 2 from dual union all
5 select 3 from dual union all
6 select 4 from dual union all
7 select 4 from dual;
Table created
SQL> select col1 from t;
COL1
1
1
2
3
4
4
6 rows selected
SQL> select distinct col1 from t;
COL1
1
2
3
4
SQL> select unique col1 from t;
COL1
1
2
3
4
SQL> select col1 from t group by col1;
COL1
1
2
3
4
SQL> select col1
2 from ( select col1
3 , row_number() over (partition by col1 order by col1) rn
4 from t
5 )
6 where rn=1;
COL1
1
2
3
4 -
Maintaining distinct counts in summary tables - thoughts
Hi,
We have a 3bn row transaction fact table of sales by product_id and customer_id.
We have some very large summaries on this. e.g product/multiple.
Wish to add at the summary leveks a distinct count of customers whio have been supplied or returned at these aggregate levels.
At moment,code merges into summary tables latest batch of data on daily basis. Fine for sums, but when updating the summary table only want to read the latest batch of data, rather than having to scan the entire lower level table to get the count(distinct)
How can we efficiently increment the counts but ensuring only increemnt if a brand new customer being supplied.
Mat. views impractical at this stage due to volume of data.
Many ThanksHello,
So if you have a calculation(Webi) function(Excel) built into the two tables you are using from the data source you might try 'configuring' the data as 'Occurance' from the workspace you created or after the file in index if you're using excel. If you are using a universe as a data source for the exploration view set you can attempt to drag the 'measure' needed (count) into the workspace option "measure" when creating the workspace.
I do hope this helps -
Distinct count using lookup table
How can I get a distinct count of column values using a different table?
Let's say I want to get a distinct count of all "company_name" records in table "emp" that corespond (match) with "lookup" table, "state" category.
What I want is to find counts for all companies that have a value of "california" in the "state" column of the "lookup" Table. I want the output to look like:
Sears 17
Pennys 22
Marshalls 6
Macys 9
I want the result to show me the company names dynamically as I don't know what they are, just that they are part of the "state" group in the lookup Table. Does this make sense?
MMark,
In the future you might consider creating test cases for us to work with. Something similar to the following where sample data is created for each table as the union all of multiple select statementsselect 'INIT_ASSESS' lookup_type
, 1 lookup_value
, 'Initial Assessment' lookup_value_desc
from dual union all
select 'JOB_REF', 2, 'Job Reference' from dual union all
select 'SPEC_STA', 3, 'SPEC STA' from dual;
select 'INIT_ASSESS' rfs_category
, 1 val
from dual union all
select 'JOB_REF', 1 from dual union all
select 'JOB_REF', 1 from dual union all
select 'SPEC_STA', null from dual;Then we can either take your select statements and make them the source of a CTAS (create table as) statementcreate table lookup as
select 'INIT_ASSESS' lookup_type
, 1 lookup_value
, 'Initial Assessment' lookup_value_desc
from dual union all
select 'JOB_REF', 2, 'Job Reference' from dual union all
select 'SPEC_STA', 3, 'SPEC STA' from dual;, or include them as subfactored queries by using the with statement:with lookup as (
select 'INIT_ASSESS' lookup_type
, 1 lookup_value
, 'Initial Assessment' lookup_value_desc
from dual union all
select 'JOB_REF', 2, 'Job Reference' from dual union all
select 'SPEC_STA', 3, 'SPEC STA' from dual
), RFS as (
select 'INIT_ASSESS' rfs_category
, 1 val
from dual union all
select 'JOB_REF', 1 from dual union all
select 'JOB_REF', 1 from dual union all
select 'SPEC_STA', null from dual
select lookup_value_desc, count_all, count_val, dist_val
from lookup
join (select rfs_category
, count(*) count_all
, count(val) count_val
, count(distinct val) dist_val
from RFS group by rfs_category)
on rfs_category = lookup_type;Edited by: Sentinel on Nov 17, 2008 3:38 PM -
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 to select distinct values from a table when it has composite primary ke
Hi
I have the requirement like , I need to select distinct one column values from the table which has composite primary key. How to acheive this functioinality using view object.
Eg : Table 1 has col1 and col2, col3
col1 col2 col3
1 A NA
1 B NA
2 A NA
3 C NA
2 D NA
primary key (col1,col2)
I have to select distinct col1.
ThanksHi
I got the solution for above. By Creating the read only view object we can acheive this.
thanks -
File to Jdbc: how to get record count from DB table
Hello,
i have a scenario file to JDBC....ihave to insert input file data to DB table.
now my requirement is ..if i insert a file with 50 records to db table on first time, and then next time if i insert the file with 100 records to db table....the count should start from 51 in db table.
if i insert another file 3rd time, with 25 records, the count shold start from 151...so how can i achieve this functionality....
i think following options:
1. in mapping write lookup to call JDBC sender channel and fetch count and map same to target filed of DB. if this is ok...please provide UDF code..2. db triggers (not suitable for my req.)
So kindly let meknow possible solutions and required UDF codes..please
Thanks in advance...SARAN>>>..if i insert a file with 50 records to db table on first time, and then next time if i insert the file with 100 records to db table....the count should start from 51 in db table.
if i insert another file 3rd time, with 25 records, the count shold start from 151...so how can i achieve this functionality....
i think following options:
Suggestions:
1)Create an id column in db table. Talk to DB guy to create oracle sequencer for that column. So, every time you insert record that field will be updated with oracle sequencer. You dont need to handle this.
Refer this link
http://www.techonthenet.com/oracle/sequences.php
2) If you want to handle via pi, following suggestions..
If you use PI 7.1 or above, use jdbc lookup in the mapping and do the query something like this
Refer this link
/people/jin.shin/blog/2008/02/15/sap-pi-71-mapping-enhancements-series-graphical-support-for-jdbc-and-rfc-lookups
Do select query as below
select count(*) from tablename;
the above query will return number of rows exist in the table. So use that value and map it in the target field.
If you use pi 7.0 or below then use the previous reply and do the UDF implementation for jdbc lookup during mapping. Because jdbc lookup does not support in those versions.
Hope that helps.
Baskar -
Getting counts from detail tables
I have multiple record bock that displaye a list of cell ids and their attributes; each record also displays record counts of its 3 detail tables.
Originally, the POST-QUERY trigger select the counts (3 detail tables) as part of the data block for each record (or cell id). There are over 16K records, so each record query issues 3 selects. The whole query toke over a minute. I was asked to improve the retrieval time.
At first I thought perhaps I could put the 3 counts in 3 separate data blocks and issue one query each in a "select cell_id, count(*). . . group by cell_id" but scrolling would not synchronize with the other blocks. So I dropped that idea.
Next, I added a program unit from which the WHEN-NEW-FORM-INSTANCE trigger calls after execute_query. It issues "select cell_id, count(*). . . group by cell_id" (one for each detail table) and fills the count columns in the original data block. However I need to set the block property Query All Records to YES so that the cell ids and attributes are filled first. That means that before the form comes up it has to retrieve all records. That saves me about 10-15 seconds od retrieval time and I lose the ability to quickly bring up the form.
Then I looked at using dfferent Query Data Source Types. I don't think I could do one query with counts of detail tables. Besides, some items (attrinutes) of the cell are upate-able.
Any ideas and suggestions will be appreciated.Yes. I suggested adding columns to the master tables and introduce stored triggers.
Since the change is not trivial, according to management, they put in on hold.I'm not sure if you misunderstood my suggestion or were responding to a different post. The query I wrote was for counting the detail records on the fly rather than populating new columns. If you include the counting in your main query then you will probably not have a much slower query than if you don't show any counts at all. Scrolling through the block will be no slower than if you had no counts, because no extra processing needs to be done. (You'll still have to fetch the detail blocks for each row, so moving to the last record will still be slow - that's a bad indicator of the performance of a query.)
For example, fetching the objects for each user takes 5 seconds. When I include the number of tables, indexes and constraints for each user within the query the time only goes up to just under 9.
SQL> set autot trace stat
SQL> set timing on
SQL> SELECT
2 owner,
3 object_name,
4 object_type
5 FROM all_objects ao;
39062 rows selected.
Elapsed: 00:00:05.13
Statistics
4656 recursive calls
0 db block gets
85106 consistent gets
0 physical reads
0 redo size
1469372 bytes sent via SQL*Net to client
29021 bytes received via SQL*Net from client
2606 SQL*Net roundtrips to/from client
0 sorts (memory)
0 sorts (disk)
39062 rows processed
SQL> SELECT
2 owner,
3 object_name,
4 object_type,
5 (SELECT Count(*) FROM all_tables WHERE owner = ao.owner) count_tables,
6 (SELECT Count(*) FROM all_indexes WHERE owner = ao.owner) count_indexes,
7 (SELECT Count(*) FROM all_constraints WHERE owner = ao.owner) count_constraints
8 FROM all_objects ao;
39062 rows selected.
Elapsed: 00:00:08.86
Statistics
4656 recursive calls
0 db block gets
270299 consistent gets
0 physical reads
0 redo size
1684042 bytes sent via SQL*Net to client
29021 bytes received via SQL*Net from client
2606 SQL*Net roundtrips to/from client
0 sorts (memory)
0 sorts (disk)
39062 rows processed
SQL> If you populate the counts in post-query then the process is similar to the block below. I tried to get a timing and stats for this but it took over 15 minutes so I shut it down.
DECLARE
ct NUMBER;
ci NUMBER;
cc NUMBER;
BEGIN
FOR ao IN (SELECT owner, object_name, object_type FROM all_objects)
LOOP
SELECT Count(*) INTO ct FROM all_tables WHERE owner = ao.owner;
SELECT Count(*) INTO ci FROM all_indexes WHERE owner = ao.owner;
SELECT Count(*) INTO cc FROM all_constraints WHERE owner = ao.owner;
END LOOP;
END;Creating a view on the query and writing the "instead of" triggers is hopefully a trivial enough operation that management won't get in the way. Then you'll be able to update the block. -
Select Distinct rows from 3 tables
I need to retrive information from 3 different tables by applying a specific condition.
I have the following query which works fine for retrieving desired data from 2 tables.
SELECT
a.userId
FROM userGeneral
a inner
join userSpecific
b on a.userId
= b.userId
WHERE
a.userActive
= 1
userId
111
222
333
444
Now I have a third table called userMgr which may contain multiple records for each userId with a corresponding mgrId value. It has a primary key identity column called userRecId and I would like to fetch the
mgrId value corresponding to the MAX(userRecId) for the matching userId.
userRecId | userId | mgrId
1 | 111 | 123
2 | 111 | 234
3 | 111 | 345
4 | 333 | 345
5 | 333 | 456
The resultset should be as follows after joining all the 3 tables.
userId | mgrId
111 | 345
222 | NULL
333 | 456
444 | NULL
Can anyone please help with this query.I need to retrive information from 3 different tables by applying a specific condition.
I have the following query which works fine for retrieving desired data from 2 tables.
SELECT
a.userId
FROM userGeneral
a inner
join userSpecific
b on a.userId
= b.userId
WHERE
a.userActive
= 1
userId
111
222
333
444
Now I have a third table called userMgr which may contain multiple records for each userId with a corresponding mgrId value. It has a primary key identity column called userRecId and I would like to fetch the
mgrId value corresponding to the MAX(userRecId) for the matching userId.
userRecId | userId | mgrId
1 | 111 | 123
2 | 111 | 234
3 | 111 | 345
4 | 333 | 345
5 | 333 | 456
The resultset should be as follows after joining all the 3 tables.
userId | mgrId
111 | 345
222 | NULL
333 | 456
444 | NULL
Can anyone please help with this query.
try this:
select userId,userRecId,
from userMgr,
(SELECT a.userId, max(a.userRecId)
FROM userGeneral a inner join userSpecific b on a.userId = b.userId
group by a.userId
WHERE a.userActive = 1) table1(userId,userRecId)
where userMgr.userRecId = table1.userRecId -
Report with multiple COUNT columns with counts from same table
I am new to discoverer so I am a bit lost.
I am working to create a report to show usage data from the eBusiness Knowledge Base. I have the query written in SQL using subqueries that is in the format:
Solution Number | Soultion Title | Solution Views | Positive Feedback | Negative Feedback
12345 ___________ Title ________ 345 ____________ 98 _______________ 34
The 'Views', 'Positive' and 'Negative' entries are stored in the same table so i am doing a count where setid=setid and usedtype=VS, then counting where usedtype=PF and usedtype=NF
In discoverer I can get the solution number, title and ONE of the totals but I can't seem to figure out how to get a COUNT for three different things from the same table in columns on the same row.
When I go to edit sheet -> select items once I select the COUNT option for the UsedType column in the table CS_KB_SET_USED_HISTS I can't select it again. I also have found now way to add a column based on an entered query.
If anyone could help it would be much appreciated.
Thanks
Edited by: Toolman21 on Dec 2, 2010 2:17 PM
added ______ to correct spacing.Hi,
You can separate the column by using a case or decode.
for example create 2 calculations:
case
when usedtype='PF'
then <you original column> --- the one contain them both
else 0
end
case
when usedtype='NF'
then <you original column> --- the one contain them both
else 0
end
after that you can create the count aggregation over those.
Tamir -
Select Distinct rows from multiple tables
Table 1 is a List of Vendors - VID, PID, VName, VAddress, VPhone
Table 2 is a list of Products - PID, PName, PPrice, PWeight, PColor
I need to produce a list of unique PID's showing the following fields - PID, VName, PName, PColor
So, Here is my failed attempt:
SELECT P.PID, V.VName, P.PName, P.PColor
FROM Products P INNER JOIN Vendors V ON P.PID = V.PID
GROUP BY P.PIDIf you post DDL, sample data and your desired output based on that sample data, someone can probably create a query that does what you want.
And I have to tell you that Table 1 is not a list of vendors unless you have a system where a vendor provides one and only one product - something that is unusual. If your system is one where a vendor should provide any number of products (and if a product
can be provided by any number of vendors), you have some fundamental schema issues to correct.
Lastly, there are sticky posts at the top of the forum that provide suggestions for posting questions. Please have a look - help your readers help you by providing sufficient information. Phrases such as "failed" or "does not work"
do not provide any useful detail. And one good rule of thumb - any time you feel you need to use (or say) distinct in a query is an indication that something somewhere is wrong. It could be a schema issue, a misunderstanding of the schema or the
goal, an incorrect query, etc. There are few instances where distinct is needed in a well-defined and implemented system, IMO. -
Union dates and count(*) from different tables
Hope you can help. Using Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
I have tables called apples, oranges, and pears. I want to get a count of all apples, oranges, pears and a total for a date range in one query statement. Any ideas?
for apples the sql is select count(apple_types) from apples where apple_date > TO_DATE('2012-01-01')
for oranges the sql is select count(orange_types) from orange where orange_date > TO_DATE('2012-01-01')
for pears the sql is s elect count(pear_types) from pears where pears_date > TO_DATE('2012-01-01')
EXAMPLE DATA
Data for apples
2012-01-01 4
2012-04-23 1
Data for oranges
2012-02-13 5
2012-03-11 2
Data for pears
2012-01-01 11
I would like the output to be
date count(apple_types) count(orange_types) count(pear_types) total
2012-01-01 4 0 11 15
2012-02-13 0 5 0 5
2012-03-11 0 2 0 2
2012-04-23 1 0 0 1here is one with pivot
WITH apples
AS (SELECT TO_DATE ('2012-01-01', 'yyyy-mm-dd') dt, 4 cnt FROM DUAL
UNION ALL
SELECT TO_DATE ('2012-04-23', 'yyyy-mm-dd') dt, 1 cnt FROM DUAL),
oranges
AS (SELECT TO_DATE ('2012-01-13', 'yyyy-mm-dd') dt, 5 cnt FROM DUAL
UNION ALL
SELECT TO_DATE ('2012-03-11', 'yyyy-mm-dd') dt, 2 cnt FROM DUAL),
pears
AS (SELECT TO_DATE ('2012-01-01', 'yyyy-mm-dd') dt, 11 cnt FROM DUAL),
t
AS ( SELECT dt, SUM (cnt) cnt, 'apples' fruit
FROM apples
GROUP BY dt
UNION ALL
SELECT dt, SUM (cnt), 'oranges'
FROM oranges
GROUP BY dt
UNION ALL
SELECT dt, SUM (cnt), 'pears'
FROM pears
GROUP BY dt)
SELECT dt,
NVL (apples, 0),
NVL (oranges, 0),
NVL (pears, 0),
NVL (apples, 0) + NVL (oranges, 0) + NVL (pears, 0) total
FROM t PIVOT (MAX (cnt)
FOR fruit
IN ('apples' AS apples, 'oranges' AS oranges, 'pears' AS pears))
ORDER BY 1
DT NVL(APPLES,0) NVL(ORANGES,0) NVL(PEARS,0) TOTAL
1/1/2012 4 0 11 15
1/13/2012 0 5 0 5
3/11/2012 0 2 0 2
4/23/2012 1 0 0 1
Maybe you are looking for
-
Need help setting up an Oracle BPA Local Server
I would like to make my computer the server and enable other users to connect to my Oracle BPA database. Is there an easy way to setup my computer? I tried having another user add my IP address as the server location using the "Add Server" option in
-
Set system-wide Finder view preferences
I know that .DS_Store files are created in every directory I enter with the finder in Mac OS X, and that keeps track of the folder's metadata (including how is it being displayed). I also know that this command: sudo find /Users/[USERNAME]/ -name ".D
-
Re-write 32bit chroot daemon in systemd service format?
I followed the Arch wiki instructions quite successfully and have been using the daemon script to use a 32bit chroot. I just switched over fully to systemd (at least I think so) and no longer have the ability to start it since rc.conf no longer exist
-
Why is the Hulu Plus interface so bad?
Why is the Hulu Plus interface so bad? The Hulu Plus interface that is presented on my Sony Blue Ray player (BDPS1500) is very difficult to access my Queue to play the shows I always watch. When you access Hulu Plus it should immediately display "You
-
Automatically Load JavaScript Files in PagePhaseListener
Hello. In my application I want to load JavaScript files automatically on each page load or navigation. It can be done by using af:resource, but what I want that in my application I do not want to load each and every JavaScript files for every page.