Creating rows in select query
Hi,
I have a column in my query that controls the number of times that row needs to be returned by the query ...
For eg
with test as
( select 'abc' as col1 , '123' as col2 , 1 as numtimes from dual
UNION ALL
select 'def' as col1 , '456' as col2 , 2 as numtimes from dual
UNION ALL
select 'ghi' as col1 , '789' as col2 , 3 as numtimes from dual
select * from test
which returns
COL1 COL2 NUMTIMES
abc 123 1
def 456 2
ghi 789 3
Now I want the second row to be returned 2 times and the third row 3 times (based on numtimes)
Is there an SQL way of doing this ...
Any help would be really appreciated
If you are on 11gR2 one way is to use recursive with clause as below
with test as
select 'abc' as col1 , '123' as col2 , 1 as numtimes from dual
UNION ALL
select 'def' as col1 , '456' as col2 , 2 as numtimes from dual
UNION ALL
select 'ghi' as col1 , '789' as col2 , 3 as numtimes from dual
rec(col1, col2, numtimes, cntr) as
select col1, col2, numtimes, 1 cntr
from test
union all
select col1, col2, numtimes, cntr + 1
from rec
where cntr < numtimes
select col1, col2, numtimes
from rec order by col1, col2Edited by: user10857924 on Apr 11, 2011 10:15 AM
Similar Messages
-
"Create Table from select Query" Vs "Insert into"
Hi
Schenaio:
My Select Query returns more than 10 million records, these records needs to be inserted into another table.
Approach 1:
I created table called TABLE1, and inserted the records using INSERT statement as a batch (batch size is 5000).
Approach 2:
I create table like,
CREATE TABLE TABLE1 AS <SELECT QUERY>
Here Apporach-1 took almost 40 minutes to complete the insert but Approach-2 took only 6 minutes.
If anybody knows why it is? And is there any way to improve the performance of Approach-1?.
Thanks
NidhiMost "batch" methods execute the same query multiple times. Row filtering is done after the rows are fetched from the source. The process of fetching all the rows could be a FullTableScan.
Therefore, a FullTableScan is executed for each batch of 5000 rows.
However, your query and batch definitions may well be different. We haven't seen the query and the execution plan.
Another point : How are you "filtering" the rows (i.e the second execution inserts rows 5001 to 10000 and does not attempt to reinsert rows 1 to 5000) ?
What is the overhead imposed by the filter ? (does the third execution have to exclude rows 1 to 10000 and inserts rows 10001 to 15000 and so on)
Hemant K Chitale -
How to take Cartesian product on logical subsets of rows in SELECT query?
Hi All,
I have the following data in seg_tab table.
Seg_no
Seg_value
1
01
2
001
2
002
3
100040
3
100041
3
100042
3
100043
Expected result, which is produced by joining the logical subsets (by seg_no) in rows. The segments can vary, for simplicity it is 3 but it can grow upto any level.
Codes
01.001.100040
01.001.100041
01.001.100042
01.001.100043
01.002.100040
01.002.100041
01.002.100042
01.002.100043
The SQL statements required to create tables and populate it with the data is given below:
CREATE TABLE seg_tab (seg_no NUMBER, seg_value VARCHAR2(10));
--1st Subset
INSERT INTO seg_tab VALUES (1,'01');
--2nd Subset
INSERT INTO seg_tab VALUES (2,'001');
INSERT INTO seg_tab VALUES (2,'002');
--3rd Subset
INSERT INTO seg_tab VALUES (3,'100040');
INSERT INTO seg_tab VALUES (3,'100041');
INSERT INTO seg_tab VALUES (3,'100042');
INSERT INTO seg_tab VALUES (3,'100043');
Any help on guiding how to write the SQL statement will be highly appreciated.
Many Thanks
Kind Regards,
BilalAnother way
with
seg_tab as
(select 1 seg_no,'01' seg_value from dual union all
select 2,'001' from dual union all
select 2,'002' from dual union all
select 3,'100040' from dual union all
select 3,'100041' from dual union all
select 3,'100042' from dual union all
select 3,'100043' from dual
concatenator(seg,codes) as
(select seg_no,seg_value
from seg_tab
where seg_no = 1
union all
select s.seg_no,c.codes || '.' || s.seg_value
from concatenator c,
seg_tab s
where s.seg_no = c.seg + 1
select codes
from concatenator
where seg = (select max(seg_no) from seg_tab)
order by codes
CODES
01.001.100040
01.001.100041
01.001.100042
01.001.100043
01.002.100040
01.002.100041
01.002.100042
01.002.100043
Regards
Etbin -
I'm using SQL Server 2008 R2 (10.50.4033) and I'm troubleshooting an issue that a select query against a specific view is taking more than 30 seconds consistently. The issue just starts happening this week and there is no mass changes in data.
The problem only occur if the query is issued from an IIS application but not from SSMS. One thing I noticed is that sys.dm_exec_cached_plans is returning 2 Parse Tree rows for the view - one created when the select query is issued
1st time from the IIS application and another one created when the same select query is issued 1st time from SSMS. The usecounts of the Parse Tree row for the view (the IIS one) is increasing whenever the select query is issued. The
usecounts of the Parse Tree row for the view (the SSMS one) does not increase when the select query is issued again.
There seems to be a correlation between the slowness of the query and the increasing of the usecounts of the Parse Tree row for the view.
I don't know why there is 2 Parse Tree rows for the view. There is also 2 Compiled Plan rows for the select query.
What does the Parse Tree row mean especially the usecounts column?>> The issue just starts happening this week and there is no mass changes in data.
There might be a mass changes in the execution plan for several reason without mass changes in data
If you have the old version and a way to check the old execution plan, and compare to the new one, that this should be your starting point. In most cases you don't have this option and we need to monitor from scratch.
>> The problem only occur if the query is issued from an IIS application but not from SSMS.
This mean that we know exactly what is the different and you can compare both execution plan. once you do it, you will find that they are no the same. But this is very common issue and we can know that it is a result of different SETting while connecting
from different application. SSMS is an external app like any app that you develop in Visual studio but the SSMS dose not use the Dot.Net default options.
Please check this link, to find the full explanation and solutions:
http://www.sommarskog.se/query-plan-mysteries.html
Take a look at sys.dm_exec_sessions for your ASP.Net application and for your SSMS session.
If you need more specific help, then we need more information and less stories :-)
We need to see the DDL+DML+Query and both execution plans
>> What does the Parse Tree row mean
I am not sure what you mean but the parse tree represents the logical steps necessary to execute the query that has been requested. you can check this tutorial about the execution plan: https://www.simple-talk.com/sql/performance/execution-plan-basics/ or
this one: http://www.developer.com/db/understanding-a-sql-server-query-execution-plan.html
>> regarding the usecount column or any other column check this link:
https://msdn.microsoft.com/en-us/library/ms187404.aspx?f=255&MSPPError=-2147217396.
Ronen Ariely
[Personal Site] [Blog] [Facebook] -
Identify tablspace in create table as select
I am trying to run a create table as select query that specifies which tablspace to create the table in. When I run the query below I get an error, any ideas?
create table roi_call_record_backup as (select * from prod.roi_call_record)
tablespace roi_data01;
nullTry this ...
create table roi_call_record_backup
tablespace roi_data01
as
(select * from prod.roi_call_record)
null -
What is the syntax for creating global temporary table using a select query
hii
I'm creating a global temporary table using a select query ..how to mention 'on commit preserve rows' that?
create global temporary table t1 as select * from trn_ordbase on commit preserve rows;
but this is invalid syntax,so how to mention on commit preserve rows in this???if i dont mention it ,by default its considering as on commit delete rows.
Please help me out of this problem.create global temporary table t1 as select * from trn_ordbase on commit preserve rows;You CANNOT use this syntax.
http://download-east.oracle.com/docs/cd/B19188_01/doc/B15917/sqcmd.htm
http://download-east.oracle.com/docs/cd/B19188_01/doc/B15917/glob_tab.gif
http://download-east.oracle.com/docs/cd/B19188_01/doc/B15917/cre_tabl.gif -
Single row from this query without create a group by
Can I have a single row from this query without create a group by on tipo (TIPO can have only 2 value (A,D)
SELECT
CASE TIPO
WHEN 'D' THEN SUM(IMPORTO) ELSE 0 END DIMPORTO,
CASE TIPO
WHEN 'A' THEN SUM(IMPORTO) ELSE 0 END AIMPORTO
FROM MGIORNALE
WHERE K_CONTO = '100001' --CONTO
AND DECODE(T_MOVIM,'MRAP',TO_DATE('31/12/'||to_char(a_competenza),'DD/MM/YYYY'),DATA_RG)
-- BETWEEN DATAA AND DATAB
BETWEEN '01/01/2006' AND '31/12/2006'
--GROUP BY TIPO
--AND TIPO = COL_conto
Thanks in advanceIs like this?
sum (CASE TIPO
WHEN 'D' THEN IMPORTO ELSE 0 END) DIMPORTO, -
Select query for rows where condition 1
Say I have a table, tb1, that has the following entries:
FName LName
Code
John Doe
xxx
Jane Doe
xxx
Steve Harper
x
Barrak Obama
x
George Bush
xxxx
Bill Clinton
xx
I'd like to write a select query that only lists the rows where the count for Code is > 1, i.e not display the last two rows from the above entry. How would I go about writing that select query.
Thanks.Please 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.
>> Say I have a table, tb1, that has the following entries: <<
Are you this rude or really ignorant and too lazy to read the Netiquette at the start to this forum? Why do you think you do not need a key? No DDL? No constraints? And , why, why do you think that “tb1” is a precise, ISO-11179 conforming table name?
Let's make this a table of rude posters rated on a 4-star scale.
CREATE TABLE Rude_Posters
(first_name VARCHAR(15) NOT NULL,
last_name VARCHAR(15) NOT NULL,
PRIMARY KEY (first_name, last_name),
rudeness_code VARCHAR (4) NOT NULL
CHECK (rudeness_code IN ('x', 'xx', 'xxx', 'xxxx'));
INSERT INTO Rude_Posters
VALUES
('John', 'Doe', 'xxx'),
('Jane', 'Doe', 'xxx'),
('Steve', 'Harper', 'x'),
('Barrack', 'Obama', 'x'),
('George', 'Bush', 'xxxx'),
('Bill', 'Clinton', 'xx');
>> I'd like to write a SELECT query that only lists the rows where the count for rudeness_code is > 1, i.e not display the last two rows from the above entry. <<
The rudeness scale is based on stars, so to ask for an integer value is like saying “on a scale from 1 to 10, what is the color of your favorite letter of the alphabet?”
Next, the number of stars and your narrative do not match. Did you want to say WHERE rudeness_code IN ('xx' 'xxx', 'xxxx')?
Please stop programming SQL until you have gotten more education. At this point, you do not know enough to ask a question.
--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 -
Using case when statement in the select query to create physical table
Hello,
I have a requirement where in I have to execute a case when statement with a session variable while creating a physical table using a select query. let me explain with an example.
I have a physical table based on a select table with one column.
SELECT 'VALUEOF(NQ_SESSION.NAME_PARAMETER)' AS NAME_PARAMETER FROM DUAL. Let me call this table as the NAME_PARAMETER table.
I also have a customer table.
In my dashboard that has two pages, Page 1 contains a table with the customer table with column navigation to my second dashboard page.
In my second dashboard page I created a dashboard report based on NAME_PARAMETER table and a prompt based on customer table that sets the NAME_ PARAMETER request variable.
EXECUTION
When i click on a particular customer, the prompt sets the variable NAME_PARAMETER and the NAME_PARAMETER table shows the appropriate customer.
everything works as expected. YE!!
Now i created another table called NAME_PARAMETER1 with a little modification to the earlier table. the query is as follows.
SELECT CASE WHEN 'VALUEOF(NQ_SESSION.NAME_PARAMETER)'='Customer 1' THEN 'TEST_MART1' ELSE TEST_MART2' END AS NAME_PARAMETER
FROM DUAL
Now I pull in this table into the second dashboard page along with the NAME_PARAMETER table report.
surprisingly, NAME_PARAMETER table report executes as is, but the other report based on the NAME_PARAMETER1 table fails with the following error.
Error Codes: OPR4ONWY:U9IM8TAC:OI2DL65P
State: HY000. Code: 10058. [NQODBC] [SQL_STATE: HY000] [nQSError: 10058] A general error has occurred. [nQSError: 16001] ODBC error state: S1000 code: 1756 message: [Oracle][ODBC][Ora]ORA-01756: quoted string not properly terminated. [nQSError: 16014] SQL statement preparation failed. (HY000)
SQL Issued: SET VARIABLE NAME_PARAMETER='Novartis';SELECT NAME_PARAMETER.NAME_PARAMETER saw_0 FROM POC_ONE_DOT_TWO ORDER BY saw_0
If anyone has any explanation to this error and how we can achieve the same, please help.
Thanks.Hello,
Updates :) sorry.. the error was a stupid one.. I resolved and I got stuck at my next step.
I am creating a physical table using a select query. But I am trying to obtain the name of the table dynamically.
Here is what I am trying to do. the select query of the physical table is as follows.
SELECT CUSTOMER_ID AS CUSTOMER_ID, CUSTOMER_NAME AS CUSTOMER_NAME FROM 'VALUEOF(NQ_SESSION.SCHEMA_NAME)'.CUSTOMER.
The idea behind this is to obtain the data from the same table from different schemas dynamically based on what a session variable. Please let me know if there is a way to achieve this, if not please let me know if this can be achieved in any other method in OBIEE.
Thanks. -
How can i update rows in a table based on a match from a select query
Hello
How can i update rows in a table based on a match from a select query fron two other tables with a update using sqlplus ?
Thanks Glenn
table1
attribute1 varchar2 (10)
attribute2 varchar2 (10)
processed varchar2 (10)
table2
attribute1 varchar2 (10)
table3
attribute2 varchar2 (10)
An example:
set table1.processed = "Y"
where (table1.attribute1 = table2.attribute1)
and (table1.attribute2 = table3.attribute2)Hi,
Etbin wrote:
Hi, Frank
taking nulls into account, what if some attributes are null ;) then the query should look like
NOT TESTED !
update table1 t1
set processed = 'Y'
where exists(select null
from table2
where lnnvl(attribute1 != t1.attribute1)
and exists(select null
from table3
where lnnvl(attribute2 != t1.attribute2)
and processed != 'Y'Regards
EtbinYes, you could do that. OP specifically requested something else:
wgdoig wrote:
set table1.processed = "Y"
where (table1.attribute1 = table2.attribute1)
and (table1.attribute2 = table3.attribute2)This WHERE clause won't be TRUE if any of the 4 attribute columns are NULL. It's debatable about what should be done when those columns are NULL.
But there is no argument about what needs to be done when processed is NULL.
OP didn't specifically say that the UPDATEshould or shouldn't be done on rows where processed was already 'Y'. You (quite rightly) introduced a condition that would prevent redo from being generated and triggers from firing unnecessarily; I'm just saying that we have to be careful that the same condition doesn't keep the row from being UPDATEd when it is necessary. -
How to get number of rows return in SELECT query
i'm very new in java, i have a question:
- How to get number of rows return in SELECT query?
(i use SQL Server 2000 Driver for JDBC and everything are done, i only want to know problems above)
Thanks.make the result set scroll insensitve, do rs.last(), get the row num, and call rs.beforeFirst(), then you can process the result set like you currently do.
String sql = "select * from testing";
PreparedStatement ps =
con.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
ResultSet rs = ps.executeQuery();
rs.last();
System.out.println("Row count = " + rs.getRow());
rs.beforeFirst();~Tim
NOTE: Ugly, but does the trick. -
How to create a triangle view with a select query?
I need help to build a select query that will create a triangle view.
Below is the table I have to query
*{color:#ff0000}INITIAL TABLE{color}*
*{color:#008000}AMOUNT | TRANSACTION_DATE | OPEN_DATE | TYPE{color}*
5 | 30-JAN-09 | 10-JAN-09 | A
10 | 12-JAN - 09 | 30-NOV-08 | A
20 | 30 - DEC - 08 | 15-OCT-08 | A
10 | 30 - DEC - 08 | 8 - OCT - 08 | A
*{color:#ff0000}THE FINAL TABLE I HAVE TO CREATE:{color}*
DEV_PERIOD - TO_CHAR(TRUNC(TRANSACTION_DATE,'Q'),'YYYY-Q') AS DEV_PERIOD
OPEN PERIOD - TO_CHAR(TRUNC(OPEN_DATE,'Q'),'YYYY-Q') AS OPEN_PERIOD
{color:#008000}*SUM of AMOUNT | DEV_PERIOD | OPEN_PERIOD | TYPE*{color}
5 | 2009 - 1 | 2009 - 1 | A
40 | 2009 - 1 | 2008 - 4 | A
30 | 2008 - 4 | 2008 - 4 | A
{color:#ff0000}*This is another view of the table (The triangle view)*{color}
| Dev_Period 2008- 1 | 2008 - 2| 2008 -3 | 2008 - 4 | 2009 -1 |
Open_Period |
2008 - 1..................... 0.......... 0............ 0........... 0.......... 0
2008 - 2 ..................................0............ 0........... 0.......... 0
2008 - 3................................................. 0........... 0.......... 0
2008 - 4 ..............................................................30......... 40
2009 - 1 .............................................................................5
Any ideas will be appreaciated.
Thank you!I think the first thing you need to do is look up "pivot query" in this newsgroup. And how complicated your query gets to be will depend on your database version (11 natively supports pivot queries). You have a variable number of columns in your result set (depending on how many quarters you have in your data.
I think once you get the columns sorted out, working out the numbers to put in each column will be relatively easy.
Jon -
How to create a Type Object with Dynamic select query columns in a Function
Hi Every One,
I'm trying to figure out how to write a piplined function that executes a dynamic select query and construct a Type Object in order to assigned it to the pipe row.
I have tried by
SELECT a.DB_QUERY INTO actual_query FROM mytable a WHERE a.country_code = 'US';
c :=DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(c,actual_query,DBMS_SQL.NATIVE);
l_status := DBMS_SQL.EXECUTE(c);
DBMS_SQL.DESCRIBE_COLUMNS(c, col_cnt, rec_tab);
FOR j in 1..col_cnt LOOP
DBMS_SQL.DEFINE_COLUMN(c,j,v_val,2000);
END LOOP;
FOR j in 1..col_cnt LOOP
DBMS_SQL.COLUMN_VALUE(c,j,v_val);
END LOOP;
But got stuck, how to iterate the values and assign to a Type Object from the cursor. Can any one guide me how to do the process.
Thanks,
mallikj2Hi Justin,
First of thanks for your reply, and coming to my requirement, I need to report the list of items which are there in the dynamic select statement what am getting from the DB. The select statement number of columns may vary in my example for different countries the select item columns count is different. For US its '15', for UK it may be 10 ...like so, and some of the column value might be a combination or calculation part of other table columns (The select query contains more than one table in the from clause).
In order to execute the dynamic select statement and return the result i choose to write a function which will parse the cursor for dynamic query and then iterate the values and construct a Type Object and append it to the pipe row.
Am relatively very new for these sort of things, welcome in case of any suggestions to make it simple (Instead of the function what i thought to work with) also a sample narrating the new procedure will be appreciated.
Thanks in Advance,
mallikj2. -
How to create a DB Adapter with select query having inner query
Hi All,
I am trying to create a DB Adapter with select query. The query has some inner queries in it. It is just like this select a, b, c, (select d from e) d, (select e from e) e from tablename.
The problem here is with the xsd generated for this query. Xsd is not getting generated properly for all the fields it is just getting generated till c element and when it encounters
the inner query it is stopping the generation of xsd. So for the above query the xsd is something similar to the below
<xs:complexType name="rewOutput">
<xs:sequence>
<xs:element name="a" type="xs:string" nillable="true"/>
<xs:element name="b" type="xs:string" nillable="true"/>
<xs:element name="c" type="xs:string" nillable="true"/>
<xs:element name="select_d" type="xs:string" nillable="true"/>
</xs:sequence>
</xs:complexType>
as shown above the xsd is just getting generated till the first inner query. What should be done to get the full fledged xsd. Should it be manually built ?? Please help me on this.
Thanks In Advance.
Edited by: 959766 on Nov 30, 2012 1:20 AMHi,
I don't think the parser will be able to understand your query properly... I would try building the xsd manually...
Cheers,
Vlad -
Cursor in select query in row to column format
Hi
I have the query like below
SELECT d.department_id,
CURSOR(SELECT e.first_name,
e.last_name
FROM employees e
WHERE e.department_id = d.department_id
) emps
FROM depatments dI want the result set in a format of Row To columns like
10 20
<cursor result> <cursor result>pls give ur suggestions how to achieve this in a efficient way?I tried the method of "max(decode(.." but dont think so its possible with thisvishnu prakash wrote:
Hi
I have the query like below
SELECT d.department_id,
CURSOR(SELECT e.first_name,
e.last_name
FROM employees e
WHERE e.department_id = d.department_id
) emps
FROM depatments dI want the result set in a format of Row To columns like
10 20
<cursor result> <cursor result>pls give ur suggestions how to achieve this in a efficient way?I tried the method of "max(decode(.." but dont think so its possible with thisNumber of column of a select query is static. Must be known at the parsing time itself. But in your case i dont think the number of columns will be limited to 2 (10 and 20) there could be many more.
You can search this forum to see how to PIVOT your data. There are lot of example. You can also try dynamic pivot. Its all in here, just search.
Maybe you are looking for
-
There are display issues with the latest Reader 11.0.03 & 10.1.7 Update with PDFs produced by Quicken PDF Printer from Quicken 2013 (Amyuni PDF Converter 4.0.0.7 producing a PDF version 1.3). The latest update has made the text (not images) unreadab
-
I have a 6520 that says its connectedwirelessly but the printer wont print now
Hi, I have a HP6520 that worked for about a day when I got it, then THe printer would become disconnected (from devices and printers ((turn gray)) what I had to do was turn the printer off, then back on, and i could get a few documents through (abou
-
Payment terms - due date on a particular day of the week say friday?
Experts is it possible in SAP payment terms to configure a term such that due date is on a particular day of the week? I want use payment term to determine due date for weekly billing cycle (sunday to saturday) for the invoice to be due on Friday net
-
Hi All Trying to open raw files in PS 7.0 can anybody help please? Gary
-
Apache setup in 10.3.9, enable documentroot
Hi, I've been using the personal web sharing feature of os x for a while now and can access all work in my sites folder from http://localhost/~digitalpencil/ I understand however, that you can also access apache through the webserver documentroot? i.