Help build a query!
There are two tables. One is composed of members with fresh and then fixed percentile. I need to build a single query based on the following1. need to know the number of members who report to a beach fixed percent 10%, 40%, 50%. Suppose, total non-member = 50 then
10%-> 5
40%--> 20
50%--> 25
2. now, I need to order the members in accordance with their costs. Thus, if he follows the expenses of members sorted by cost
A1 100
A2 99
A3 98
A4 97
A5 96
A6 95
.....
.....
A50 50
then
the total expenses should be discovered as
10% [sum of the first 5: A1 to A5] = 100 + 99 + 98 + 97 + 96 = 490
40% [sum of the next 20: A6 to A26]
50% [sum of the next 25: of the A27 to A50]
Help, please!
Published by: Fanny on January 11, 2010 07:50
Fanny says:
I can try, follow these steps. But I need to improvise the query.
No problem:
with t as (
select 'A' || level member,101 - level expenses from dual connect by level < 51
)
select b.label,
sum(a.expenses) total_expenses
from (
select row_number() over(order by expenses desc) rn,
count(*) over() cnt,
expenses
from t
) a,
(
select seq_id,
label,
cumulative_percent,
lag(cumulative_percent,1,0) over(order by seq_id) prev_cumulative_percent
from groups
) b
where a.rn > a.cnt * b.prev_cumulative_percent / 100 -- you can wrap it with round
and a.rn <= a.cnt * b.cumulative_percent / 100 -- depending on your requirements
group by b.label,
b.seq_id
order by b.seq_id
/
LABEL TOTAL_EXPENSES
-------------------- --------------
10% 490
40% 1710
50% 1575
SQL>
Table A calculates the number of members and each sequential member the number of current Member in descending order of their spending. Table B calculates, for each cumulative percentage of the previous sequence id id. So now, table B, each line defines a bucket. Now, all we need is to join A and B send each Member to bucket appropriate.
SY.
Tags: Database
Similar Questions
-
In order to explain my problem, I'll give my data first and then explain what I am trying to accomplish.
Oracle: 10g
Table = tb.xInfo
"So what I try to do based on the above data is: summarize all specific amounts, exit it years in years like 1995-1997 column" and all styles of there in the column style, with Chris, I want out of his STYLE values separated by a comma.NAME STYLE YEAR AMOUNT SEC_ID BOB BLUE 1995 6 1 BOB BLUE 1996 8 1 BOB BLUE 1997 7 1 CHRIS RED 1995 4 1 CHRIS PURPLE 1996 8 1 CHRIS RED 1997 5 1 DAN YELLOW 1995 9 1 DAN YELLOW 1996 4 1 DAN YELLOW 1997 1 1
Desired result set
This is the code I tried but did not have much success:NAME STYLE YEAR AMOUNT BOB BLUE 1995-1997 21 CHRIS RED, PURPLE 1995-1997 17 DAN YELLOW 1995-1997 14
The above doesn't seem to work.select name, (CASE WHEN count(style) = 2 THEN STYLE || ', ' || STYLE ELSE STYLE END) as style, '1995-1997' AS YEAR SUM(AMOUNT) as amount from ( select name, style, year, amount from tb.xInfo where year in (1995,1996,1997) and sec_id = 1 and name ) Group by name, style, amount
Hello
Here is an example of SYS_CONNECT_BY_PATH, using the example of data published by Mwooldridge:
WITH got_style_num AS ( SELECT DISTINCT name , style , SUM (amount) OVER ( PARTITION BY name) AS total_amount , DENSE_RANK () OVER ( PARTITION BY name ORDER BY style ) AS style_num FROM msw_test WHERE year IN (1995, 1996, 1997) AND sec_id = 1 ) SELECT name , LTRIM ( SYS_CONNECT_BY_PATH (style, ', ') , ', ' ) AS styles , '1995-1997' AS years , total_amount FROM got_style_num WHERE CONNECT_BY_ISLEAF = 1 START WITH style_num = 1 CONNECT BY style_num = PRIOR style_num + 1 AND name = PRIOR name ;
Create dynamically the years column, as did Mwooldrige, is a good idea. To modify the above query, use the MIN and MAX functions analytical in the subquery got_style_num.
Alternatively, you can use the SYS_CONNECT_BY_PATH to generate a string like ' 1995, 1996, 1997. This could be very useful if some names, it was missing a few years; then you might get results like ' 1995, 1997' or '1995' dynamically.The above query lists the styles alphabetically. In the sample data you posted, you RED prior to VIOLET. If it's important, explains what order you want.
-
Hello
Please help build a sql query
My Table Test2015 has given belowHeader_id Line_id Ordered_item
723887290 199925 MAIN1
199925 723887291 MAIN2
199926 723887292 SH-POS-NO-BR POS-INS
199926 723887293 MAIN2
199927 723887294 IC-ENV-NON-BR-ENV-PXY
199927 723887295 MAIN1
199927 723887297 MAIN2
199927 723887298 PRCSS SH-FAIRY-ELEC DISTR.
199927 723887299 SH-FAIRY-SUM PRO-DE-CONS-HOUSE
I am trying to query my Test2015 table to obtain the records with ordered_item containing 'MAIN1' and 'MAIN2' only. I tried to write a query as below
SELECT * FROM test2015 WHERE ORDERED_ITEM in ('MAIN1', 'MAIN2');
But it gives me all the data with the MAIN2 records found but MAIN1 is absent, I want to retrieve only records to both 'MAIN1' and 'MAIN2' present for Header_id.
While the result below shows me header_id - 199926 and 199929 that he should assume back. I want to fetch documents only with 'MAIN1' and 'MAIN2' both present.
Header_id Line_id Ordered_item
723887290 199925 MAIN1
199925 723887291 MAIN2
199926 723887293 MAIN2
199927 723887295 MAIN1
199927 723887297 MAIN2
199929 723887299 MAIN1
Please suggest.
Thank you and best regards,
Prasad.
Hello
Try like this...
SELECT * FROM test2015 WHERE ORDERED_ITEM in ('MAIN1") and in header_id (select test2015 WHERE ORDERED_ITEM in ('MAIN2') header_id)
-
Oracle Version: 11.2.0.2.0
I need assistance with the output of the query. Here is the table.
With Tbl_Nm as
(
Select 'ABC1' SYSTEM_ID, REGION 'US', 'CHI' SUB_REGION 4000 BALANCE, to_date('1-JUN-2012 10:45:00 am', 'dd-mon-yyyy hh:mi:ss am') LAST_UPD_TIME, 'A' FLAG of union double all the
Select 'PQR2', 'UK', 'LN', 2000, To_Date('1-JUL-2012 10:46:00 am', 'dd-mon-yyyy hh:mi:ss am'), has ' starting from dual Union All
Select 'ABC1', 'IND","MAMA", 3500, To_Date('1-AUG-2012 11:47:00 am', 'dd-mon-yyyy hh:mi:ss am'), 'A' from dual Union All
Select "LMN3", "US", "NJ", 2500, To_Date('1-SEP-2012 09:49:00 am', 'dd-mon-yyyy hh:mi:ss am'), 'A' from dual Union All
Select "PQR2", "UK", "MC", 2600, To_Date('1-OCT-2012 04:45:00 am', 'dd-mon-yyyy hh:mi:ss am'), 'A' from dual Union All
Select 'ABC1', 'US', 'NY', 3200, To_Date('1-OCT-2012 06:45:00 am', 'dd-mon-yyyy hh:mi:ss am'), has ' starting from dual Union All
Select "LMN3", "UK", "BT", 2400, To_Date('1-NOV-2012 07:45:00 am', 'dd-mon-yyyy hh:mi:ss am'), has ' From Dual
)
Select * from tbl_nm
I need the output below.
PQR2 UK MC 2600 1 OCTOBER 2012 04:45
ABC1 US NY 3500 October 1, 2012 06:45
LMN3 UK BT 2500 November 1, 2012 07:45
The need the disc according to this system_id flagged as "A". But if the last disc of 'd' then it must show that the amount, but the file should be displayed in 'A '.
I've tried a few and got stuck. Help, please. Not able to get a balance '.
This question is a bit similar to needing help with a query result
With Tbl_Nm as
(
Select 'ABC1' System_Id, region 'US', 'CHI' Sub_Region, 4000 balance, To_Date('1-JUN-2012 10:45:00 am', 'dd-mon-yyyy hh:mi:ss am') Last_Upd_Time, 'A' flag of double Union All
Select 'PQR2', 'UK', 'LN', 2000, To_Date('1-JUL-2012 10:46:00 am', 'dd-mon-yyyy hh:mi:ss am'), has ' starting from dual Union All
Select 'ABC1', 'IND","MAMA", 3500, To_Date('1-AUG-2012 11:47:00 am', 'dd-mon-yyyy hh:mi:ss am'), 'A' from dual Union All
Select "LMN3", "US", "NJ", 2500, To_Date('1-SEP-2012 09:49:00 am', 'dd-mon-yyyy hh:mi:ss am'), 'A' from dual Union All
Select "PQR2", "UK", "MC", 2600, To_Date('1-OCT-2012 04:45:00 am', 'dd-mon-yyyy hh:mi:ss am'), 'A' from dual Union All
Select 'ABC1', 'US', 'NY', 3200, To_Date('1-OCT-2012 06:45:00 am', 'dd-mon-yyyy hh:mi:ss am'), has ' starting from dual Union All
Select "LMN3", "UK", "BT", 2400, To_Date('1-NOV-2012 07:45:00 am', 'dd-mon-yyyy hh:mi:ss am'), has ' From Dual
)
Select System_Id, region, Sub_Region, Balance, Last_Upd_Time of Tbl_Nm T1
where t1. Last_Upd_Time = (select max (Last_Upd_Time) in the Tbl_Nm T2 where T1.) SYSTEM_ID = T2. SYSTEM_ID)
So maybe you'd then
ORDER BY DECODE(flag,'D',9,1) ASC...
to get the Ds at the end of the list.
or
ORDER BY CASE WHAT flag = has ' (your other filters) AND then 9 or 1 end CSA,...
HTH
-
Build the query to select date with status
Hi guys,.
Grateful if you can advise me on how to build the query on below scenario:
Table A
Date
11.44.39.000000000 12-OCT-14 AM ASIA/SINGAPORE
11.44.35.000000000 16-SEP-14 AM ASIA/SINGAPORE
11.44.42.000000000 22-SEP-14 AM ASIA/SINGAPORE
The result of the query:
Date Status
11.44.39.000000000 12-OCT-14 AM ASIA / SINGAPORE inactive
11.44.35.000000000 16-SEP-14 active AM ASIA/SINGAPORE
11.44.42.000000000 22-SEP-14 AM ASIA/SINGAPORE inactive
Basically, the logic, I wanted is
Active principles: today date or max (date) < sysdate
Otherwise will be inactive
And there is 1 active date in time.
Thanks in advance
Hello
2753165 wrote:
Hi guys,.
Grateful if you can advise me on how to build the query on below scenario:
Table A
Date
11.44.39.000000000 12-OCT-14 AM ASIA/SINGAPORE
11.44.35.000000000 16-SEP-14 AM ASIA/SINGAPORE
11.44.42.000000000 22-SEP-14 AM ASIA/SINGAPORE
The result of the query:
Date Status
11.44.39.000000000 12-OCT-14 AM ASIA / SINGAPORE inactive
11.44.35.000000000 16-SEP-14 active AM ASIA/SINGAPORE
11.44.42.000000000 22-SEP-14 AM ASIA/SINGAPORE inactive
Basically, the logic, I wanted is
Active principles: today date or max (date)<>
Otherwise will be inactive
And there is 1 active date in time.
Thanks in advance
Sorry, we don't know what you want.
Are you saying that 1 row (maximum) can be assigned status = 'Active' and if 2 or more lines are eligible, the last of them will be called 'Active'?
If so:
CASE
WHEN tmstmp<=>=>
OR ROW_NUMBER () OVER (PARTITION BY CASE
WHEN tmstmp<=>=>
THEN "could be."
ANOTHER 'No Way'
END
ORDER BY tmstmp DESC
) = 1
THEN "active."
ELSE 'inactive '.
END
If you would care to post CREATE TABLE and instructions INSERT for some samples, so I could test it.
DATE is not a very good name for a column, especially if the column is a TIMESTAMP, not a DATE. I called the TMSTMP instead of the DATE column.
-
Dialog box that says ' Creative Cloud Installer wants to make changes. Type your password for this purpose"- I type my password for Adobe ID (creative cloud), but it will not accept it. who should I go for help with this query?
It does not ask the cloud your computer admin password password!
-
Help with the query to select only one record from the result set in double
Hello
Please help with the query. Version of Oracle database we use is 10g R2.
I have a vision that is duplicated IDS, but they are used across the different functions. See below examples of data. Please help me with a query to select only one record (based on ID regardless of the area) from the bottom of the result set of duplicate records. For what is the point of view is there unique records, given the combination of the fields ID, Org, DF, dry, Sub-Sec
ID Org DF Sec Sub-Sec (163) CQ CPDM CPDM HD (163) PC ENG ENG ENG (163) CQ ASIC ASIC IS 8888 TS TAC TAC TAC (163) TS HE HE SW 6789 CQ INFO INFO FOS 6789 PC SECSYS SECSYS INFO1 6789 TS SECSYS SECSYS INFO2 9009 PC BMS BMS BMS1 My result set must eliminate the duplicate identifiers regardless of whoever we choose of the result set. (I mean without distinction Org, DF, s, Sub-s). My expected result set should be.
ID DSB DF SEC Sub-Sec (163) CQ CPDM CPDM HD 8888 TS TAC TAC TAC 6789 CQ INFO INFO FOS 9009 PC BMS BMS BMS1 Thank you
Orton
Hello
This sounds like a job for ROW_NUMBER:
WITH got_r_num AS
(
SELECT id, DSB, df, s, sub_sec org
ROW_NUMBER () OVER (PARTITION BY ID.
ORDER BY org
) AS r_num
OF view_x
)
SELECT id, DSB, df, sub_sec s,
OF got_r_num
WHERE r_num = 1
;
He is a Top - N query example, where you choose the elements of N (N = 1 in this case) from the top of an ordered list.
I hope that answers your question.
If not, post a small example of data (CREATE TABLE and INSERT, only relevant columns instructions) to your sample data and the results desired from these data. (I know that you said that you were a view selection. Just for this thread, pretending it is a picture and post simple CREATE TABLE and INSERT statements to simulate your point of view).
Point where the above query is to produce erroneous results, and explain, using specific examples, how you get the right results from data provided in these places. (I didn't quite understand the explanation above. I don't know why you want toID ORG DF DRY SUB_SEC
-- --- -- --- -------
1234 CQ DPRK DPRK HD
and is not
1234 IS CQ ASIC, ASIC
or
TS 1234 IT IT SW
or
1234 CQ ASIC ASIC HD
)
If you change the query at all, post your modified version.
Always say what version of Oracle you are using (for example, 11.2.0.2.0).See the FAQ forum: https://forums.oracle.com/message/9362002
-
Please, help me to query SQL Construct.
Hi Experts,Could you please help me to query SQL Construct. Please find the details
HOSTNAME HOSTTYPE DEM R1 R2
RS123 P ABC 24.5 265,5RS123 P CYC 24.5 265,5
RS123 P ADDS 24.5 265,5
RS123 P ADE 24.5 265,5
RS123 P SRC 24.5 265,5
EXPECTED RESULTS
HOSTNAME HOSTTYPE MNE R1 R2
RS123 P ABC, CYC, ADD, ADE, CBC 24.5 265,5Concerning
See you soon
with t as)
Select "RS123' hostname 'P' hosttype, 'ABC' dem, 24.5 r1, r2 265,5 Union double all the
Select 'RS123', 'P', "CYC", 24.5, 265,5 double Union all
Select 'RS123', 'P', 'ADD', 24.5, 265,5 double Union all
Select "RS123', 'P', 'ADE', 24.5, 265,5 double Union all
Select 'RS123', 'P', 'SRC', 24.5, 265,5 double
)
Select the host name,
HostType,
RTrim (XMLAGG (XmlElement(e,MNE,','). (Extract ('//Text ()')), ',') DEM,.
R1,
R2
t
Group hostname,
HostType,
R1,
R2
/
HOSTN H DEM R1 R2
----- - -------------------- ---------- ----------
RS123 P ABC, CBC, ADE, ADD, CYC 24.5 265,5SQL >
SY.
-
Hello!
I m facing a problem with the help of oraext: query-database.
In my transformation im try the following (Simplified):
How to get the correct value when you use oraext:query - database?<xsl:template match="*"> <xsl:variable sqlQuery="select ....."/> <xsl:variable name="storeSec" select="oraext:query-database($sqlQuery,true(),true(),'jdbc/xref')/> <xsl:choose> <xsl:when test="string-length($storeSec/ROWSET/ROW[1]/STORE_PART_SECTION) > 0"> <xsl:value-of select="$storeSec/ROWSET/ROW[1]/STORE_PART_SECTION"/> </xsl:when> <xsl:otherwise> <xsl:value-of select"some other val"/> </xsl:otherwise> </xsl:choose> </xsl:template> {code} This always results in +some+ +other+ +val+ !! I´v checked the output from oraext:query-database by using getcontentAsString and if I instead test putting the expected output from oraext:queryDatabase in my variable it gives me A100 which is what i expected. {code} <xsl:template match="*"> <xsl:variable sqlQuery=select ....."/> <xsl:variable name="storeSec"> <ROWSET> <ROW num="1"> <STORE_PART_SECTION>A100</STORE_PART_SECTION> </ROW> <ROW num="2"> <STORE_PART_SECTION>XXm</STORE_PART_SECTION> </ROW> </ROWSET> </xsl:variable> <xsl:choose> <xsl:when test="string-length($storeSec/ROWSET/ROW[1]/STORE_PART_SECTION) > 0"> <xsl:value-of select="$storeSec/ROWSET/ROW[1]/STORE_PART_SECTION"/> </xsl:when> <xsl:otherwise> <xsl:value-of select"some other val"/> </xsl:otherwise> </xsl:choose> </xsl:template>
How should you exit? Several item ID with each having a value of the result set?
If Yes, then you can try following: -
procedure that will dynamically build the query data and table Medallion
Hi people,
I write a procedure that dynamically build the query data and insert in the table "dq_summary".
enforcement procedure with success and data not inserted into the table 'dq_summary '.
I have thin problem in code attached below
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------FOR rep IN cur_di_attr LOOP dbms_output.put_line ('d: '); BEGIN EXECUTE IMMEDIATE 'SELECT table_name FROM ' || sum_tab || ' WHERE id = ' || rep.attribute_id INTO rep_tab; dbms_output.put_line ('rep_tab: '||rep_tab); run_query := run_query || ' ' || rep_tab || ' WHERE ' || nvl(wh_cond, '1 = 1'); EXECUTE IMMEDIATE run_query INTO end_rslt; EXECUTE IMMEDIATE 'UPDATE dq_summary SET ' || prop || '_' || p_code || ' = ' || end_rslt || ' WHERE attribute_id = ' || rep.attribute_id; dbms_output.put_line ('e: '); dbms_output.put_line ('rep_tab: '||rep_tab); dbms_output.put_line ('end_rslt: '||end_rslt); dbms_output.put_line ('f: '); EXCEPTION WHEN no_data_found THEN rep_tab := ''; sum_tab := ''; END; END LOOP;
but in the procedure below must be run several times
Published by: BluShadow on February 7, 2012 12:04create or replace PROCEDURE DQ_REPORT_PROC AS prop di_proposition.pro_name%type; col_var VARCHAR2(100); p_code dq_parameter.para_code%type; sum_tab di_proposition.summary_table%type; run_query dq_parameter.run_query%type; wh_cond dq_parameter.where_cond%type; end_rslt VARCHAR2(20); rep_tab VARCHAR2(50); v_error_msg VARCHAR2(200); v_error_code VARCHAR2(200); v_object_name VARCHAR2(50) DEFAULT 'DQ_REPORT_PROC'; v_iss_no VARCHAR2(20) DEFAULT NULL; CURSOR cur_di_prop IS SELECT upper(replace(replace(pro_name, ' '),'-')) pro_name FROM di_proposition; CURSOR cur_di_para IS SELECT upper(para_code) para_code, run_query, where_cond FROM dq_parameter; CURSOR cur_di_attr IS SELECT attribute_id FROM dq_summary; BEGIN DELETE FROM dq_summary; INSERT INTO dq_summary (attribute_id, entity_name, attribute_name, data_champ) SELECT a.attribute_id, b.entity_name, a.attribute_name, a.data_champ FROM di_attribute_master a, di_entity_master b WHERE a.entity_id = b.entity_id; FOR c_prop IN cur_di_prop LOOP prop := c_prop.pro_name; BEGIN SELECT distinct SUBSTR(column_name, 1, INSTR(column_name, '_')-1), summary_table INTO col_var, sum_tab FROM user_tab_cols a, di_proposition b WHERE a.table_name = 'DQ_SUMMARY' AND upper(replace(replace(b.pro_name, ' '),'-')) = prop AND SUBSTR(a.column_name, 1, INSTR(a.column_name, '_')-1) = upper(replace(replace(b.pro_name, ' '),'-')) AND upper(b.status) = 'Y'; dbms_output.put_line ('col_var: '||col_var); dbms_output.put_line ('sum_tab: '||sum_tab); EXCEPTION WHEN no_data_found THEN col_var := ''; sum_tab := ''; END; dbms_output.put_line ('a: '); FOR para IN cur_di_para LOOP dbms_output.put_line ('b: '); p_code := para.para_code; run_query := para.run_query; wh_cond := para.where_cond; dbms_output.put_line ('c: '); FOR rep IN cur_di_attr LOOP dbms_output.put_line ('d: '); BEGIN EXECUTE IMMEDIATE 'SELECT table_name FROM ' || sum_tab || ' WHERE id = ' || rep.attribute_id INTO rep_tab; dbms_output.put_line ('rep_tab: '||rep_tab); run_query := run_query || ' ' || rep_tab || ' WHERE ' || nvl(wh_cond, '1 = 1'); EXECUTE IMMEDIATE run_query INTO end_rslt; EXECUTE IMMEDIATE 'UPDATE dq_summary SET ' || prop || '_' || p_code || ' = ' || end_rslt || ' WHERE attribute_id = ' || rep.attribute_id; dbms_output.put_line ('e: '); dbms_output.put_line ('rep_tab: '||rep_tab); dbms_output.put_line ('end_rslt: '||end_rslt); dbms_output.put_line ('f: '); EXCEPTION WHEN no_data_found THEN rep_tab := ''; sum_tab := ''; END; END LOOP; END LOOP; END LOOP; COMMIT; EXCEPTION WHEN OTHERS THEN v_error_msg := SQLERRM; v_error_code := SQLCODE; TRACKER_LOG_EXECEPTION(v_iss_no, v_object_name, CURRENT_TIMESTAMP, v_error_msg, v_error_code); COMMIT; END DQ_REPORT_PROC;
addition of {noformat}{noformat} tags. Please read {message:id=9360002} and learn to do this yourself in future.
903830 wrote:
I write a procedure that dynamically build the query data and insert in the table "dq_summary".
enforcement procedure with success and data not inserted into the table 'dq_summary '.I'm sorry. But there is no kind of say that way. The code is undesirable. The approach is wrong. This will not happen. This will cause the fragmentation of memory in the shared Pool. This will lead to another session being impossible to analyze the sliders because of the fragmented memory.
Not only that. The underlying data model is questionable.
All this seems a candidate perfect as an example of how NOT to design and code and use Oracle.
-
need help with the query, thx
Hello
I need a little help with the query I have to write;
the table has 4 columns:
what I am asking is the following result: salary according to the latest available yearcol1 col2 col3 col4 emp_name empl_id salary year content of data: col1 col2 col3 col4 smith 12 1200 1999 smith 12 1340 2000 smith 12 1500 2001 jones 13 1550 1999 jones 13 1600 2000 aron 14 1200 2002
i.e.
ID appreciate some guidance on how to achievesmith 12 1500 2001 jones 13 1600 2000 aron 14 1200 2002
Thank you
Rgdsselect *from (select col1, col2,col3, col4,row_number() over(partition by col1 order by col4 desc) rn from
) where rn=1 -
Hi gurus
need help with this query,
I want to display the records in the table emp
I want just the recordsSQL> Select Deptno,sal,sal/SUMSAL Percent,rn 2 From ( Select emp.*,Sum(Sal) Over() "SUMSAL",Row_number() Over(Order by sal Desc) rn 3 From emp 4 ) 5 / EMPNO DEPTNO SAL PERCENT RN --------- ---------- ---------- ---------- ---------- 7839 10 5000 .172265289 1 7902 20 3000 .103359173 2 7788 20 3000 .103359173 3 7566 20 2975 .102497847 4 7698 30 2850 .098191214 5 7782 10 2450 .084409991 6 7499 30 1600 .055124892 7 7844 30 1500 .051679587 8 7934 10 1300 .044788975 9 7521 30 1250 .043066322 10 7654 30 1250 .043066322 11 7876 20 1100 .037898363 12 7900 30 950 .032730405 13 7369 20 800 .027562446 14 14 rows selected.
Thank youEMPNO DEPTNO SAL PERCENT RN ---------- ---------- ---------- ---------- ---------- 7839 10 5000 .172265289 1 7902 20 3000 .103359173 2 7788 20 3000 .103359173 3 7566 20 2975 .102497847 4 7698 30 2850 .098191214 5 with sum (Percent) of remaing records..... Others .420327304
Published by: SeenuGuddu on February 27, 2011 03:39with a as ( Select Empno, Deptno ,sal, sal/SUMSAL Percent, case when rn<=5 then rn else null end rnm From (Select emp.*, Sum(Sal) Over() "SUMSAL", Row_number() Over(Order by sal Desc) rn From emp) ) select case when max(rnm) is not null then to_char(max(empno)) else 'Others:' end empno, case when max(rnm) is not null then max(deptno) else null end deptno, case when max(rnm) is not null then max(sal) else null end sal, to_char(sum(percent), '90.99') percent, max(rnm) rn from a group by rnm order by rnm
EMPNO DEPTNO SAL PERCENT RN ---------------------------------------- ---------------------- ---------------------- ------- ---------------------- 7839 10 5000 0.17 1 7902 20 3000 0.10 2 7788 20 3000 0.10 3 7566 20 2975 0.10 4 7698 30 2850 0.10 5 Others: 0.42 6 rows selected
-
small request I have given as below,
Month ProductNo CustomerNo units
9001 1001 Jan - 09 100
9002 1002 Jan - 09 200
9003 1003 Jan - 09 300
Jan 9001 400 ABCCustomer
9002 1004 Jan - 09 500
for all record - if column - customerNo starts with digital it must show as CN_ * other wise of the same name.
Result must be
9001 100 CN_1001-09 Jan
9002 200 CN_1002-09 Jan
9003 300 CN_1003-09 Jan
Jan 9001 400 ABCCustomer
9002 500 CN_1004-09 Jan
Can help get the queryA logic that is easier to implement this is as below
SQL> with t as (select 'jan' Month, 9001 ProductNo,'1001-09' CustomerNo,100 Units from dual union all 2 select 'jan', 9002, '1002-09', 200 from dual union all 3 select 'jan', 9003, '1003-09', 300 from dual union all 4 select 'jan', 9001, 'ABCCustomer', 400 from dual union all 5 select 'Jan', 9002, '1004-09', 500 from dual) 6 select month,productno,case when upper(substr(customerno,1,1))=lower(substr(customerno,1,1)) 7 then 'CN_'||customerno else customerno end customerno,units from t; MON PRODUCTNO CUSTOMERNO UNITS --- ---------- -------------- ---------- jan 9001 CN_1001-09 100 jan 9002 CN_1002-09 200 jan 9003 CN_1003-09 300 jan 9001 ABCCustomer 400 Jan 9002 CN_1004-09 500
TRY WITH THIS upper (substr(customerno,1,1)) = lower (substr(customerno,1,1))
-
Hi Experts,
I have a DB table has columns of more than 50.
I question this table, it should only return one line at any time. as sqldeveloper below image.
here, I need to build block pl/sql-query, Discover the column in the table as a key and query result as values.
Eg: Key - Value
TASK_EVENT_ID - 1765
EVENT_TYPE - ASR_UPDATE
... etc until all of the columns in my table.
Experts please comment on that point, appreciate your help on this.
Thank you
-Vincent.
Here is an approach using DBMS_SQL to iterate over the columns of key / value to assign... (Little code snipped for brevity)
create or replace procedure (task_expired)
v_store_id in full,
v_task_action_id in full,
v_job_id in full
)
as
-[SNIP code...]
v_sql VARCHAR2 (4000): = ' select * from my_table where PK = 123'; -Your SQL here!
v_v_val VARCHAR2 (4000);
v_n_val NUMBER;
v_d_val DATE;
v_ret NUMBER;
c NUMBER;
d NUMBER;
col_cnt INTEGER.
f BOOLEAN;
rec_tab DBMS_SQL. DESC_TAB;
col_num NUMBER;
vAsString VARCHAR2 (4000);
BEGIN
-[SNIP code...]
Message_properties. CORRELATION: = "EDF_EVENT";
MSG: = SYS. AQ$ _JMS_BYTES_MESSAGE. Construct();
Msg.set_string_property ('queueName', ' shipping/csi_cth');
Msg.set_string_property ('MODE', 'CR8');
c: = DBMS_SQL. OPEN_CURSOR;
DBMS_SQL. PARSE (c, v_sql, DBMS_SQL. NATIVE);
d: = DBMS_SQL. Execute (c);
DBMS_SQL. DESCRIBE_COLUMNS (c, col_cnt, rec_tab);
1.col_cnt J
LOOP
CASE rec_tab (j) .col_type
WHEN 2 THEN
DBMS_SQL. DEFINE_COLUMN (c, j, v_n_val); -Number
WHEN 12 CAN
DBMS_SQL. DEFINE_COLUMN (c, j, v_d_val); -Date
ON THE OTHER
DBMS_SQL. DEFINE_COLUMN (c, j, v_v_val, 2000); -Else treat as varchar2
END CASE;
END LOOP;
LOOP
v_ret: = DBMS_SQL. FETCH_ROWS (c);
WHEN OUTPUT v_ret = 0;
1.col_cnt J
LOOP
-Fetch each column to the correct data type based on coltype
CASE rec_tab (j) .col_type
WHEN 2 THEN
DBMS_SQL. COLUMN_VALUE (c, j, v_n_val);
vAsString: = to_char (v_n_val);
WHEN 12 CAN
DBMS_SQL. COLUMN_VALUE (c, j, v_d_val);
vAsString: = to_char (v_d_val, ' DD/MM/YYYY HH24:MI:SS');
ON THE OTHER
DBMS_SQL. COLUMN_VALUE (c, j, v_v_val);
vAsString: = v_v_val;
END CASE;
Msg.set_string_property (rec_tab (j) .col_name, vAsString);
END LOOP;
END LOOP;
DBMS_SQL. CLOSE_CURSOR (c);
DBMS_AQ. ENQUEUE (queue_name-online 'cbus.aqjms_common',
Enqueue_options => Enqueue_options,
Message_properties => Message_properties,
Payload-online msg,
Msgid => Message_handle);
dbms_output.put_line ('00 Msgid =' |) Message_handle);
dbms_output.put_line('===Done=');
-[SNIP code...]
END;
/
-
Need help to build the query to group the lines
Hello all, hope someone can help me with this. I am working in Oracle 11 g PL/SQL 11.2.0.2.0.
I have the following query, which does exactly what I need, but I have been invited to consolidate the results in a specific way and I can't do that. First of all the existing request:
I was asked to do, is to display a number of facility_type who have each of the combinations of the 'DEAL' 33 areas. Installation types are strings. So an expected result would look something like:SELECT facility_id ,facility_type ,COUNT (CASE WHEN component_type = 'ATTACH2NDPARTY' THEN 1 END) AS ATTACH2NDPARTY ,COUNT (CASE WHEN component_type = 'ATTACH3RDPARTY' THEN 1 END) AS ATTACH3RDPARTY ,COUNT (CASE WHEN component_type = 'BREAKERGT' THEN 1 END) AS BREAKERGT ,COUNT (CASE WHEN component_type = 'BREAKERUSS' THEN 1 END) AS BREAKERUSS ,COUNT (CASE WHEN component_type = 'CAPACIFORMER' THEN 1 END) AS CAPACIFORMER ,COUNT (CASE WHEN component_type = 'CAPACITOR' THEN 1 END) AS CAPACITOR ,COUNT (CASE WHEN component_type = 'CEFIBEROPTIC' THEN 1 END) AS CEFIBEROPTIC ,COUNT (CASE WHEN component_type = 'ELASTIDISCONN' THEN 1 END) AS ELASTIDISCONN ,COUNT (CASE WHEN component_type = 'NETWORKPROTECT' THEN 1 END) AS NETWORKPROTECT ,COUNT (CASE WHEN component_type = 'POLE' THEN 1 END) AS POLE ,COUNT (CASE WHEN component_type = 'REACTOR' THEN 1 END) AS REACTOR ,COUNT (CASE WHEN component_type = 'RECLOSER3PUPOIL' THEN 1 END) AS RECLOSER3PUPOIL ,COUNT (CASE WHEN component_type = 'RECLOSERTSUP' THEN 1 END) AS RECLOSERTSUP ,COUNT (CASE WHEN component_type = 'RECLSR3PCNTRL3A' THEN 1 END) AS RECLSR3PCNTRL3A ,COUNT (CASE WHEN component_type = 'RECLSR3PCNTRLNT' THEN 1 END) AS RECLSR3PCNTRLNT ,COUNT (CASE WHEN component_type = 'RECLSRTSCNTRL' THEN 1 END) AS RECLSRTSCNTRL ,COUNT (CASE WHEN component_type = 'RECTIFIERUSS' THEN 1 END) AS RECTIFIERUSS ,COUNT (CASE WHEN component_type = 'REGULATORJOINT' THEN 1 END) AS REGULATORJOINT ,COUNT (CASE WHEN component_type = 'REGULATOROH' THEN 1 END) AS REGULATOROH ,COUNT (CASE WHEN component_type = 'REGULATORUSS' THEN 1 END) AS REGULATORUSS ,COUNT (CASE WHEN component_type = 'RMS' THEN 1 END) AS RMS ,COUNT (CASE WHEN component_type = 'SPLICEPRIMARY' THEN 1 END) AS SPLICEPRIMARY ,COUNT (CASE WHEN component_type = 'STREETLIGHT' THEN 1 END) AS STREETLIGHT ,COUNT (CASE WHEN component_type = 'SWITCHSCADA' THEN 1 END) AS SWITCHSCADA ,COUNT (CASE WHEN component_type = 'TAPCHANGER' THEN 1 END) AS TAPCHANGER ,COUNT (CASE WHEN component_type = 'TRAFFICSIGNAL' THEN 1 END) AS TRAFFICSIGNAL ,COUNT (CASE WHEN component_type = 'TRANSF480' THEN 1 END) AS TRANSF480 ,COUNT (CASE WHEN component_type = 'TRANSFGROUND' THEN 1 END) AS TRANSFGROUND ,COUNT (CASE WHEN component_type = 'TRANSFISOLATION' THEN 1 END) AS TRANSFISOLATION ,COUNT (CASE WHEN component_type = 'TRANSFOH' THEN 1 END) AS TRANSFOH ,COUNT (CASE WHEN component_type = 'TRANSFUG' THEN 1 END) AS TRANSFUG ,COUNT (CASE WHEN component_type = 'TRANSFURD' THEN 1 END) AS TRANSFURD ,COUNT (CASE WHEN component_type = 'TRANSFUSS' THEN 1 END) AS TRANSFUSS FROM (SELECT fy.id AS facility_id ,fy.external_facility_id ,fy.flty_facility_type as facility_type ,cp.cpty_component_type as component_type FROM facilities fy LEFT OUTER JOIN components cp ON cp.facility_id= fy.id ORDER BY fy.id DESC) GROUP BY facility_id, facility_type
FACILITY_TYPE | ATTACH2NDPARTY | ATTACH3RDPARTY | BREAKERGT | ... TRANSFUSS | COUNTY
MANHOLE X X 10
MANHOLE X X 22
POLE X X 5
and so on. Because there are 33 BUSINESS areas and therefore 33! possible combinations, I was thinking about a sort of loop would achieve the desired result, but I'm stuck and could really use a shot in the arm. Any help will be appreciated and obtained points! Thanks in advance.select facility_type ,ATTACH2NDPARTY ,ATTACH3NDPARTY -- and so on , count(*) cnt from ( --your query SELECT facility_id ,facility_type ,COUNT (CASE WHEN component_type = 'ATTACH2NDPARTY' THEN 1 END) AS ATTACH2NDPARTY ,COUNT (CASE WHEN component_type = 'ATTACH3RDPARTY' THEN 1 END) AS ATTACH3RDPARTY ,COUNT (CASE WHEN component_type = 'BREAKERGT' THEN 1 END) AS BREAKERGT ... ) group by facility_type ,ATTACH2NDPARTY ,ATTACH3NDPARTY -- and so on like in projection
Maybe you are looking for
-
Firefox server not found problem
When I opened my new links on Google search results pages, sometimes I got the pages 'server not found '. I had to refresh twice like that to get the pages loaded. I searched online solutions and I had tried to disable the antivirus, turn off DNS pre
-
When I start Firefox, it happens with Yahoo, NOT with the default Firefox. If I try to reset Firefox, I get the response "well, it's embarrassing" and cannot reset. I went to the deleted control panel Firefox and downloaded and re-installed FIrefox f
-
Replacement of the graphics card for Satellite P100-188
Hello My nvidia 7600 go graphics card fell into my laptop (black screen, no vga output).Does anyone know of any other graphics cards I can use as a replacement because I can not hand on the original anywhere (it's a stand-alone card by the way, not b
-
Hi, I created a LabView executable that is running some test of framgrabbing on a camera system. The outgoing result is a Boolean value that I want to read when I return from the exe somehow. I saw that there was a way to enter arguments with this st
-
Streets & trips 2008 stopped working and now won't load
I was working with streets & trips, went to another program and returned. Clicked on the icon got the hourglass momentarily then nothing. Tried to reinstall the program without help. Thank you