Selecting duplicate rows based on a combination of columns as key
Hi ,
I have a table with 5 columns.
Code ID S_DATE E_DATE Name
1 23 01012001 null ABC
1 09 01012001 null XYZ
2 81 04022007 null TVU
1 43 03092008 null XXX
Now, I need write a select query to fetch the duplicate rows from the above table having the combination of (Code, S_DATE,E_DATE) as the key.
So from the above example, I need to get Row1 and Row2 as output (but not Row3 as it has a different S_DATE)
Thanks in advance for your suggestions.
Thanks
Edited by: thotaramesh on Mar 9, 2009 4:54 PM
On XE;
WITH sample_data AS (
SELECT 1 code,23 ID, '01012001' s_date, null e_date, 'ABC' NAME FROM dual UNION ALL
SELECT 1, 09, '01012001', null, 'XYZ' FROM dual UNION ALL
SELECT 2, 81, '04022007', null, 'TVU' FROM dual UNION ALL
SELECT 1, 43, '03092008', null, 'XXX' FROM dual)
SELECT code, ID, s_date, e_date, NAME
FROM (
SELECT
sample_data.*,
COUNT(*) over (PARTITION BY code, s_date, e_date) dups
FROM sample_data)
WHERE dups > 1;
CODE ID S_DATE E_DATE NAME
1 23 01012001 ABC
1 9 01012001 XYZ
Similar Messages
-
Query - restricting rows based on specific combinations of columns
I have two columns in two different tables T1 and T2 like below
T1.Column1 T2.Column2
1 a
2 b
3 c
4 d
5 e
I need all the combinations of values in the columns, which I can choose like
select T1.Column1, T2.Column2 from T1, T2 ------ (Without specifying any join ie. cartesian product)
But, in those, combinations, I need to restrict the following combinations, from not being selected - (1,b), (1,c),(3,b), in the same sql, or using a subquery. I am not able to achieve this after several attempts. Can any one help?Just pad it and check
SQL> select no,name from a,b where to_char(no)||name not in ('1b','1c','3b')
2 /
NO N
1 a
1 d
1 e
2 a
2 b
2 c
2 d
2 e
3 a
3 c
3 d
NO N
3 e
4 a
4 b
4 c
4 d
4 e
5 a
5 b
5 c
5 d
5 eThanks,
Karthick. -
Deleting duplicate rows based on three columns in Oracle 8i
Hi all,
The database we use is Oracle 8i.
The query below raises the too_many_rows exception when I launch an application. So I want to delete the duplicated rows :
select polarisation_1, polarisation_2
into v_pol1_tech, v_pol2_tech
from v_cfh_lien_element
where nom_lien = p_nom_lien
AND num_canal_1 = p_num_canal_1
AND freq_emise_1 = p_freq_emise_1;
Notice that with many possible values of the parameters p_nom_lien, p_num_canal_1 and p_freq_emise_1 then the exception is raised.
So how to delete generally the duplicated rows based on the three columns "nom_lien" , "num_canal_1" and "freq_emise_1" ?
Thank you very much indeed.Check the other thread with same question deleting duplicate rows based on three columns in Oracle 8i
-
Delete duplicate rows -- based on 4 columns -- how?
I asked this question on how to delete duplicates recently and received this suggestion which works well -- except --
With CTE AS
SELECT *, ROW_NUMBER() OVER (Partition by fld1 order by fld1) RowNum
FROM #tmpA
DELETE From CTE
WHERE RowNum > 1
-- the actual table I need to delete duplicate rows on is based on 4 columns. The following table contains 14,462 rows of which 14,348 are distinct -- based on the following 4 colums. Below is an image of a sample of the data contained in the
table for my question and to the right of that data is the column structures (data types). Is it possible to do something like the above example suggestion with the table in the image below? How to do that? I need to delete rows so that 14462
goes down to 14348. If I only reference one column for the delete -- this would delete like 7000+ rows. I only need to remove 114 rows.
Rich PAdd the other 3 columns to the partition.
Jason Long -
Selecting duplicate rows from table
Hi all,
How to select the duplicates rows present in the table...SQL> select * from customer;
CUST_ID CUST_NAME LOC
1 Jeff Miami
2 Andrew Michigan
3 Julia Chicago
1 Linda Miami
1 Martha Miami
3 Randy Chicago
3 John Chicago
7 rows selected.
SQL> select * from customer where rowid != (select min(rowid) from customer C where C.cust_id = customer.cust_id);
CUST_ID CUST_NAME LOC
1 Linda Miami
1 Martha Miami
3 Randy Chicago
3 John Chicago
SQL> -
How not show duplicate rows based on one field
Oracle Database 11g Enterprise Edition Release 11.2.0.3.0
Hello
I have a query that looks for certain scripts that did not run on a particular day compared to what ran the same day a week ago. We want to include the start_datetime and end_datetime but when I add it to the select statement it brings up all instances of the jobs that run multiple times during the day. Is there a way to exclude the extra rows based on the script_name field?
SELECT instances.script_name,
instances.instance_name,
REGEXP_REPLACE(master.description,
chr(49814), -- em-dash
'-') description
--instances.start_datetime
FROM xxcar.xxcar_abat_instances Instances,
xxcar.xxcar_abatch_master Master
WHERE 1 = 1
AND TRUNC(start_datetime) = TRUNC(TO_DATE(:p_StartDate, 'YYYY/MM/DD HH24:MI:SS')) - (:p_NumOfWeeks * 7)
AND Instances.SCRIPT_NAME = Master.SCRIPT_NAME (+)
MINUS
SELECT script_name,
instance_name,
NULL
--NULL
FROM xxcar.xxcar_abat_instances
WHERE 1 = 1
AND TRUNC(start_datetime) = TRUNC(TO_DATE(:p_StartDate, 'YYYY/MM/DD HH24:MI:SS'))MINUS does a set operation - removing rows from the first set that exactly match the second set.
When you add columns to the first set, you want a more restricted filtering - try a multi-column NOT IN:
To remove multiple runs, group and get min/max
SELECT instances.script_name,
instances.instance_name,
REGEXP_REPLACE(master.description,
chr(49814), -- em-dash
'-') description,
min(instances.start_datetime) start_datetime,
min(instances.end_datetime) end_datetime
FROM xxcar.xxcar_abat_instances Instances,
xxcar.xxcar_abatch_master Master
WHERE 1 = 1
AND TRUNC(start_datetime) = TRUNC(TO_DATE(:p_StartDate, 'YYYY/MM/DD HH24:MI:SS')) - (:p_NumOfWeeks * 7)
AND Instances.SCRIPT_NAME = Master.SCRIPT_NAME (+)
AND (script_name, instance_name) NOT IN
( SELECT script_name,
instance_name
FROM xxcar.xxcar_abat_instances
WHERE 1 = 1
AND TRUNC(start_datetime) = TRUNC(TO_DATE(:p_StartDate, 'YYYY/MM/DD HH24:MI:SS'))
group by instances.script_name, instances.instance_name, master.descriptionYou didn't give table definitions, and the query has schemas in it, so I didn't test it.
regards,
David -
How to programatically select a row in TableBean and update its column?
Hi,
Can anyone help me on How to programmatically select a row in a TableBean and update its column?
Thanks,
JonHi,
My requirement is I need to update a column in a particular row of the table using fire action...
I have a datefield bean serve as birhdate and base on this I need to update the age column depending on the given dates..
Here's my code under the Process form request for your reference...
if (actionInMainPersonScreen.equals("changeDate"))
String checkId = pageContext.getParameter("paramDatePersonId");
OAFormValueBean depPerId = (OAFormValueBean)depTable.findIndexedChildRecursive("ChildPersonID");
OAMessageTextInputBean depFName = (OAMessageTextInputBean)depTable.findIndexedChildRecursive("FirstName");
OAMessageDateFieldBean dateBirth = (OAMessageDateFieldBean)depTable.findIndexedChildRecursive("BDay");
OAMessageStyledTextBean age = (OAMessageStyledTextBean)depTable.findIndexedChildRecursive("Age");
Date changeBDate = new java.util.Date();
Date dateToday = new java.util.Date();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
changeBDate = (Date)dateBirth.getValue(pageContext);
Calendar cal = Calendar.getInstance();
ResultSet empAge = null;
String newAge = null;
OADBTransaction trans = personam.getOADBTransaction();
System.out.println("BirthDate: " + changeBDate + " Date Today: " + sdf.format(dateToday));
String expQuery = "SELECT Trunc((sysdate - To_Date('" + pageContext.getParameter("paramDateBirth") + "'))/365) compAge, Sysdate from dual";
System.out.println("SQL: " + expQuery);
PreparedStatement expPreparedStatement = trans.createPreparedStatement(expQuery ,1);
try
empAge = expPreparedStatement.executeQuery();
} catch (SQLException e) {}
try
while (empAge.next())
newAge = empAge.getString("compAge");
age.setText(pageContext, newAge);
empAge.close();
} catch (SQLException e) {}
regards,
Jon -
Oracle Toad 9.0- selection of rows based on timestamp
Hi,
I am using Oracle Toad 9.0 and am trying to pull records based on the timestamp they were modified.
To be more specific, i want to pull out the objects which were modified between 28th March 2011 and April 3rd 2011.
In my understanding it should return rows which were modified between 12 am 28th March till 11.59pm April 3rd,
Please let me know if this is correct..
If this is correct then i have a problem where the objects modified on April 3rd(12.00am to 11.59pm) are not being pulled.
Query used:
select * from tablename where cast(obj_mod_dt as date) between '28-Mar-2011' and '03-Apr-2011'
-- Results have objects modified from 28th March 12.00am to 02 Apr 11.59pm
Please let me know on why it behaves indifferently.select * from tablename where cast(obj_mod_dt as date) between '28-Mar-2011' and '03-Apr-2011'Is obj_mod_dt not already a DATE datatype?
Why are you comparing a DATE to strings?
I think perhaps you are looking more for something like this:
select *
from tablename
where cast(obj_mod_dt as date) between to_date('28-Mar-2011','DD-Mon-YYYY') and to_date('04-Apr-2011','DD-Mon-YYYY')-(1/86400)or
select *
from tablename
where cast(obj_mod_dt as date) >= to_date('28-Mar-2011','DD-Mon-YYYY')
and cast(obj_mod_dt as date) < to_date('04-Apr-2011','DD-Mon-YYYY')Of course if obj_mod_dt is already a date column then there's no need to cast it.
If it's not a date column, then what is it? Is it varchar2? If so you should be explicit in the conversion to a DATE datatype e.g.
where to_date(obj_mod_dt,'DD-Mon-YYYY') ...and ensure you specify the correct date format for it.
Otherwise you are relying on implicit datatype conversions and it's likely that it'll break somewhere. -
Duplicate rows based upon condition
Oracle 11.2.0.1
Windows
create table regsales (billno number,itemno number,paymode varchar2(10));
insert into regsales values (12345,10,'cash');
insert into regsales values (12345,11,'cash');
insert into regsales values (12346,11,'cash');
insert into regsales values (12347,10,'credit');
insert into regsales values (12348,14,'cash');
insert into regsales values (12348,15,'cash');
insert into regsales values (12345,12,'cash');
insert into regsales values (12349,10,'cash');
insert into regsales values (12345,10,'credit');
insert into regsales values (12350,11,'cash');
insert into regsales values (12351,12,'cash');
insert into regsales values (12352,11,'cash');
insert into regsales values (12350,11,'credit');
Required Output please :
BILLNO ITEMNO PAYMODE
12345 11 cash
12345 11 credit
12350 10 cash
12350 10 credit
i.e. in which same billnos same itemno has been sold in cash and credit.
Thank you.Hi,
So, you need to know how many different paymodes there are in a group of rows. That sounds like a job for COUNT (DISTINCT ...)
Here's one way:
WITH got_cnt AS
SELECT billno, itemno, paymode
, COUNT (DISTINCT paymode)
OVER ( PARTITION BY billno
, itemno
) AS cnt
FROM regsales
SELECT billno, itemno, paymode
FROM got_cnt
WHERE cnt = 2
ORDER BY billno, itemno, paymode
Can there be other paymodes besides 'cash' and 'credit'? If so, the same basic idea will still work, but the details may be a little messier, depending on your requirements. -
Select distinct rows based on latest date
Hi
I need to produce data from two tables and return results where only data for the latest OriginationDate is returned for each unique client. I have been trying all sorts of combinations but with no success. Any help would be appreciated
e.g
select
c.client_no
,c.forename
,c.surname
,c.tel_no1
,c.tel_no2
,c.tel_no3
,o.ordernumber
,o.propertyidentifier
,o.contractorlongname
,o.OrderStatus
,o.CancelReasonDesc
,o.OriginationDate
,o.Completed
,DATEDIFF(d,o.OriginationDate,GETDATE())
as Total
FROM
hgmclent AS c
LEFT
OUTER
JOIN QLHPM_Order_Summary
AS o
ON
c.client_no
= o.ClientNumber
WHERE
o.Ordernumber
IS
NOT
NULL
GROUP
BY c.client_no
,c.forename
,c.surname
,c.tel_no1
,c.tel_no2
,c.tel_no3
,o.ordernumber
,o.propertyidentifier
,o.contractorlongname
,o.OrderStatus
,o.CancelReasonDesc
,o.OriginationDate
,o.Completed
Currently this produces the following data from which I have hidden sensitive information. What I need to show for client_no 1 is repair order 6353 which was reported on 2015-01-06 00:00:00.000 being the most recent of 12 orders for this client,
Client No2 only has one order so this will be shown
Client No3 should only show order number 6842 reported on 2015-01-19 00:00:00.000
and so on.
Can anyone help with this
Thanks
JohnI think he needs to return the data for the latest OriginationDate, so ORDER BY o.Completed DESC should be changed to
ORDER BY o.OriginationDate DESC
Row_number() Over(Partition
by c.client_no Order
by o.OriginationDate
DESC ) rn
A Fan of SSIS, SSRS and SSAS -
Remove duplicate rows based on latest date
Hi Julius, There are various ways to achive this but I would think an optimized way of doing it by making use of (Sorter and) an Aggregator transformation(s), see how.. Sort your input records at SQ level if it's a relational source or else use a Sorter tx (that's why I mentioned Sorter tx in braces in abvoe line) to sort the input rows on Stage_ID and Date, both in Ascending order, thus you get the latest date record at the end in the list per common Stage_IDs. Now, connect to Aggregator (must be right next to the sorter in order to not to loose the sorted data), and enable the Group By for Stage_ID port. By nature, aggregator tx will push the last record of the group by port or last record of the complete data set if no group by port mentioned. So, you will get recent row per Stage_ID. Try and get back to us if you have any questions or run into issues,-Rajani
I have a target table I need to split up: stage_id / date / case / blah / blah100 / 01-jan-2015 / 223 / 32 / 323100 / 01-apr-2015 / 224 / 32 / 322 the stage_id column cannot have more than 1 of the same record, so, i need to keep the latest record (01-apr-2015) in this target table, then remove the old one and put it into a dimension table any suggestions for how to accomplish this? please let me know if more info is needed thanks!
-
Trouble with joining based on various combinations of columns
Hi
I have a load of transaction data which I need to join to a rate table to find the correct rate to price on. The join should be one-to-one and the selection of the correct rate is based on various columns in both tables which should either match or, where
the rate table contains 'NA', allow any value from the transaction table. Where there is a specific match, this should be selected rather than a join where 'NA' is used to allow any other value in the transaction.
Here is the CREATE script for the transaction table:
CREATE TABLE [dbo].[job_variables](
[job_no] [int] NOT NULL,
[product_code1] [nvarchar](2) NULL,
[product_code2] [nvarchar](2) NULL,
[customer_code] [nvarchar](8) NULL,
[area1] [nvarchar](8) NULL,
[area2] [nvarchar](8) NULL,
[group_code] [nvarchar](8) NULL)
And for the rate table:
CREATE TABLE [dbo].[ratecriteria](
[product_code1] [nvarchar](255) NULL,
[product_code2] [nvarchar](255) NULL,
[customer_code] [nvarchar](255) NULL,
[area1] [nvarchar](255) NULL,
[area2] [nvarchar](255) NULL,
[group_code] [nvarchar](255) NULL,)
The combinations used to join the tables should be attempted in this order, where X = a match and NA = ratecriteria value is 'NA' so allow all from job_variables. As the data tables need to join one-to-one, once a transaction meets the join criteria, it
cannot be joined to another ratecriteria record.
Firstly, where ratecriteria.group_code = 'NA' and customer_key matches:
product_code1
product_code2
area1
area2
customer_code
group_code
X
X
X
X
X
NA
X
X
X <------>
X
X
NA
(area1 and area2 reciprocated)
X
X
X
NA
X
NA
X
X
NA
X
X
NA
X
X
NA
NA
X
NA
NA
X
X
X
X
NA
NA
X
X
NA
X
NA
NA
X
NA
X
X
NA
NA
X
NA
NA
X
NA
Then, where ratecriteria.customer_code = 'NA' and group_code matches:
product_code1
area1
area2
customer_code
group_code
X
X
X
NA
X
X
X <------>
X
NA
X
(area1 and area2 reciprocated)
X
X
NA
NA
X
X
NA
X
NA
X
X
NA
NA
NA
X
NA
X
X
NA
X
NA
X
NA
NA
X
NA
NA
X
NA
X
NA
NA
NA
NA
X
And finally, where both ratecriteria.customer_code and ratecriteria.group_code = 'NA':
product_code1
area1
area2
customer_code
group_code
X
X
X
NA
NA
X
X <------>
X
NA
NA
(area1 and area2 reciprocated)
X
X
NA
NA
NA
X
NA
X
NA
NA
X
NA
NA
NA
NA
NA
X
X
NA
NA
NA
X
NA
NA
NA
NA
NA
X
NA
NA
NA
NA
NA
NA
NA
I am working with SQL Server 2012 in SSMS. Any help greatly appreciated, let me know if I need to provide more info.
ThanksI think that you have got that correct, although I am not entirely sure what "REFERENCES" does, I will research that one. I do know that the database design is poor but, for context, I have imported all the data I am going to use, it
is all in excellent shape and I will not do any further imports, creates, deletes, updates etc. so a poor schema should (and this may be me showing my lack of knowledge again) not matter at this stage. I am really looking for a solution to the above problem.
In terms of a query which outputs a correctly selected rate code (see above post 5th March 15:01), my solution which is perhaps a sledgehammer to crack a nut is as such.
I have created a table I have called ratecrit_junction which I use to generate all the different combinations of actual values from job_variables and 'NA' entries.
CREATE TABLE [dbo].[ratecrit_junction](
[selection_rank] INT IDENTITY(1,1),
[product_code1] [char](2),
[product_code2] [char](2),
[area1] [varchar](6),
[area2] [varchar](6),
[customer_code] [varchar](8),
[group_code] [varchar](10)
INSERT INTO ratecrit_junction
VALUES ('X', 'X', 'X', 'X', 'X', 'NA'),
('X', 'X', 'X', 'NA', 'X', 'NA'),
('X', 'X', 'NA', 'X', 'X', 'NA'),
('X', 'X', 'NA', 'NA', 'X', 'NA'),
('NA', 'X', 'X', 'X', 'X', 'NA'),
('NA', 'X', 'X', 'NA', 'X', 'NA'),
('NA', 'X', 'NA', 'X', 'X', 'NA'),
('NA', 'X', 'NA', 'NA', 'X', 'NA'),
('X', 'X', 'X', 'X', 'NA', 'X'),('X', 'X', 'X', 'NA', 'NA', 'X'),
('X', 'X', 'NA', 'X', 'NA', 'X'),
('X', 'X', 'NA', 'NA', 'NA', 'X'),
('NA', 'X', 'X', 'X', 'NA', 'X'),
('NA', 'X', 'X', 'NA', 'NA', 'X'),
('NA', 'X', 'NA', 'X', 'NA', 'X'),
('NA', 'X', 'NA', 'NA', 'NA', 'X'),
('X', 'NA', 'X', 'X', 'X', 'NA'),
('X', 'NA', 'X', 'NA', 'X', 'NA'),
('X', 'NA', 'NA', 'X', 'X', 'NA'),
('X', 'NA', 'NA', 'NA', 'X', 'NA'),
('NA', 'NA', 'X', 'X', 'X', 'NA'),
('NA', 'NA', 'X', 'NA', 'X', 'NA'),
('NA', 'NA', 'NA', 'X', 'X', 'NA'),
('NA', 'NA', 'NA', 'NA', 'X', 'NA'),
('X', 'NA', 'X', 'X', 'NA', 'X'),
('X', 'NA', 'X', 'NA', 'NA', 'X'),
('X', 'NA', 'NA', 'X', 'NA', 'X'),
('X', 'NA', 'NA', 'NA', 'NA', 'X'),
('NA', 'NA', 'X', 'X', 'NA', 'X'),
('NA', 'NA', 'X', 'NA', 'NA', 'X'),
('NA', 'NA', 'NA', 'X', 'NA', 'X'),
('NA', 'NA', 'NA', 'NA', 'NA', 'X')
I can then join data from job_variables to ratecrit_junction using a COALESCE(NULLIF(...), ...) to get the different combinations and join to ratecriteria with a ranking to indicate which one of them should override the others and identify the correct rate
code to use.
I forgot to include rate code in my original post, correction below.
CREATE TABLE [dbo].[ratecriteria](
ID INT IDENTITY(1,1) PRIMARY KEY,
[product_code1] [nvarchar](2) REFERENCES Product_Code,
[product_code2] [nvarchar](2) REFERENCES Product_Code,
[customer_code] [nvarchar](8) REFERENCES Customer_Code,
[area1] [nvarchar](8) REFERENCES Area,
[area2] [nvarchar](8) REFERENCES Area,
[group_code] [nvarchar](8) REFERENCES Group_Code,
[rate_code] [nvarchar](5),
UNIQUE (product_code1, product_code2, customer_code, group_code)
And here is the query that I am using
SELECT v.job_no,
j.selection_rank,
rc.rate_code
FROM job_variables v
CROSS JOIN ratecrit_junction j
INNER JOIN ratecriteria rc
ON COALESCE(NULLIF(j.product_code1, 'X'), v.product_code1) = rc.product_code1
AND COALESCE(NULLIF(j.product_code2, 'X'), v.product_code2) = rc.product_code1
AND COALESCE(NULLIF(j.area1, 'X'), v.area1) = rc.area1
AND COALESCE(NULLIF(j.area2, 'X'), v.area2) = rc.area2
AND COALESCE(NULLIF(j.customer_code, 'X'), v.customer_code) = rc.customer_code
AND COALESCE(NULLIF(j.group_code, 'X'), c.group_code) = rc.group_code
And here is some sample data for the job_variables and ratecriteria tables, based on my earlier post with the coloured examples.
INSERT INTO ratecriteria
VALUES ('P1', 'PP1', 'C1', 'AA', 'BB', 'NA', 'R1'),
('P1', 'PP1', 'C1', 'AA', 'NA', 'NA', 'R2'),
('P1', 'PP1', 'NA', 'AA', 'BB', 'G1', 'R3'),
('NA', 'NA', 'NA', 'NA', 'NA', 'G1', 'R4')
INSERT INTO job_variables
VALUES (1, 'P1', 'PP1', 'C1', 'AA', 'BB', 'G3'),
(2, 'P1', 'PP1', 'C1', 'BB', 'AA', 'G4'),
(3, 'P1', 'PP1', 'C1', 'AA', 'FF', 'G1'),
(4, 'P1', 'PP1', 'C2', 'AA', 'BB', 'G1'),
(5, 'P1', 'PP2', 'C1', 'AA', 'BB', 'G1'),
(6, 'P2', 'PP2', 'C4', 'AB', 'AA', 'G1') -
With out selecting the Row, display Dropdown for a perticular column
Hi,
i have a requirement to display dropdown to perticular column in a Tableview.
is it posible.....?
Regards,
BrahmajiHi,
The value of the TextEdit inside a Tableview, can be got by using the same method that you use it outside the tableview.
If you know the id of the Textview, then you could get the data inside the textview easily.
All the form fileds will be stored in form_fields table that is stored in the request object.
This also implies that the textedit value will also be stored inside the form_fields array.
The textedit value can be read from this internal table using the below syntax.
The syntax for reading the textedit value is below...
data: lv_string type string,
lv_te_iid type string.
lv_te = 'te1'.
lv_string = request->get_form_field( NAME = lv_te ).
The id of the textedit should be assigned by you, during the factory method. Say for example te_1_1 i.e. te_<row_number>_<column_no>
Later in the event handler based on the no. of questions, you could loop and form the id of the text_edit and get the value of the text edit and store the value of the textEdit in the internal table based on the row index.
Hope it helps.!
Regards,
Maheswaran
Edited by: Maheswaran B on Nov 6, 2009 10:00 PM
Edited by: Maheswaran B on Nov 6, 2009 10:02 PM -
Make 1 row turn into X rows, based on value X in column?
Hello everyone, got a question for you! I've got a table as follows:
ITEM_NUM,IN_STOCK
1001A,2
1001B,1
1001C,2
1001D,3
I'd like to get the following output:
1 1001A
2 1001A
3 1001B
4 1001C
5 1001C
6 1001D
7 1001D
8 1001D
So each row gets repeated for as many times as it has for the in_stock value. And down the left side, we get rownum.
I can do this with PL/SQL code (a cursor to get both columns, and for each row, run a loop to place these into a collection). But if there's a way just to skip the loop and write a query, I'd rather do this!
Thanks!
-Thomas HWell you can pretty much use any row source here but I favour pipelined function for overall simplicity / clarity and performance.
Personal Oracle Database 10g Release 10.1.0.2.0 - Production
With the Partitioning, OLAP and Data Mining options
SQL> CREATE TABLE t (item_num VARCHAR2 (5), in_stock NUMBER);
Table created.
SQL> INSERT INTO t VALUES ('1001A',2);
1 row created.
SQL> INSERT INTO t VALUES ('1001B',1);
1 row created.
SQL> INSERT INTO t VALUES ('1001C',2);
1 row created.
SQL> INSERT INTO t VALUES ('1001D',3);
1 row created.
SQL> CREATE OR REPLACE FUNCTION many (
2 p_rows IN NUMBER)
3 RETURN number_table PIPELINED
4 IS
5 BEGIN
6 FOR l_row IN 1..p_rows LOOP
7 PIPE ROW (l_row);
8 END LOOP;
9 RETURN;
10 END;
11 /
Function created.
SQL> SELECT ROWNUM, item_num
2 FROM t, TABLE (many (in_stock));
ROWNUM ITEM_
1 1001A
2 1001A
3 1001B
4 1001C
5 1001C
6 1001D
7 1001D
8 1001D
8 rows selected.
SQL> -
Extract duplicate rows and append them in single column
hi,
my requirement is i have the data in a table like below
GIVEN DATA
req_id res_id
100 200
100 201
101 300
102 200
102 400
102 null
THE OUTPUT SHOULD BE
req_id res_id
100 200,201
101 300
102 200,400
can anybody please help me out in writing the query to get the desired output.
*****NOTE: REMEMBER THERE ARE 100'S OF RECORDS IN THE TABLE THE ABOVE IS ONLY SAMPLE DATA.
Thanks in advance
Best Regards,SQL> with t as
2 (select 100 req_id,200 res_id from dual union all
3 select 100,null from dual union all
4 select 100,201 from dual union all
5 select 100,null from dual union all
6 select 101,null from dual union all
7 select 101,null from dual)
8 select req_id,
9 ltrim(max(sys_connect_by_path(res_id,'-')),'-') res_id
10 from(
11 select req_id,res_id,
12 row_number() over(partition by req_id order by res_id nulls first) rn
13 from t)
14 start with rn = 1
15 connect by rn = prior rn + 1
16 and req_id = prior req_id
17 group by req_id;
REQ_ID RES_ID
100 200-201
101
Maybe you are looking for
-
Idiot Internet Explorer always gave me the option of merely opening a document or saving it to my hard drive. I thought Firefox was giving me that option also, until I started realizing over the past two or three months - I've been using Firefox sinc
-
How can I display "0" instead of "#missing" in Smartview
Hi, I'm in Smartivew -> Options menu and I can put "text" or "-" in place of #missing when I retrieve. However, it would not allow me to put zero in place of "#missing" . Is there any way around that? I am connected to an Essbase server via smartview
-
Can iWeb 08 be fully functional on another Host?
I have an rather extensive site I am building with iWeb 08. I am contemplating using register.com to host my site. I read somewhere that the blogging and podcast functions, as well as commenting in those areas will NOT function on a host other than .
-
Re: Qosmio x770-136 - How to watch movies in 3D using VLC player
Hi I've just got a Qosmio X770-136 laptop. How do i work the 3d? I've got downloaded movies to play through VLC. Am i right in thinking the laptop changes them over to 3D? Mine doesnt seem to be working?
-
How Can I Share a Screen Remotely?
I know how to do it on a local network. I have a AirPort Extreme and am wanting to set it up where If I am away from home on my MacBook I can access the house and help the family with problems they often run into. I figured out how to forward my port