Group by returning multiple columns in a single request
HelloSorry to ask this simple question, I suppose, but here's my problem.
I am building a query to get to say the smallest user_id of workers in society by Department.
The query goes like:
Select emp... Department,
min (EMP.user_id)
employee emp
Emp.department group
It gives me the smallest user by Department id, which is what I want. But how can I also get the name of this person?
I know that the condition of 'min' distinguishes a single record (there are no two people with the same user_id in the Department).
But how can I also get the name without turning the query above in a subquery that I would like to once again a link to the table of employees?
I know that the following works, but I don't think it's the best option:
Select v1.department,
v1.user_id,
Emp1.name
employee emp1.
(select emp... Department,
min (EMP.user_id)
employee emp
Group emp.department) v1
where emp1.user_id = v1.user_id
This is just one example of data. This is the principle which I don't understand.
Any advice would be much appreciated.
Cyril
Hi, Cyril.
To find the name of the person who has the lowest user_id
SELECT department
, MIN (user_id) AS lowest_user_id
, MIN (name) KEEP (DENSE_RANK FIRST ORDER BY user_id) AS person_with_lowest_user_id
FROM emp
GROUP BY department;
'MIN (name)' above means that if there is a link for the lowest user_id, you will choose the candidate with the first name.
If you want to display several columns in the row with the lowest user_id, you must have an expression of 'KEEP (DENSE_RANK...)' separate for each column. In this case, you will find may be easier to use the RANK or the analytical ROW_NUMBER in a subquery, like this:
WITH sub_query AS
(
SELECT department
, user_id
, name
, col2, col3, col4, col5
, RANK () OVER ( PARTITION BY department
ORDER BY user_id
) AS r_num
FROM emp
)
SELECT * -- or list all columns EXCEPT r_num
FROM sub_query
WHERE r_num = 1;
Tags: Database
Similar Questions
-
GROUP BY with multiple columns.
I have a little query on the GROUP BY clause.
Sometimes, we will give several names of columns in GROUP BY. If it behaves in the same way as ORDER BY (multi-column) I wish I had an example where I can use GROUP BY multiple columns. in any case regardless of his behaviour, it will be really appreciated if someone can explain a scenario where GROUP BY with multiple columns can be used.
I know about the use of GROUP BY aggregate functions, but using a single column.
Thank you.. !!!No, not like that
I think that Group by does not follow any order...
If we execute like this
SELECT registrationid, dateofbirth, sum (age) FROM prawin62 WHERE registrationid = 22 GROUP BY dateofbirth, registrationid.
22 1/23/1975 54 22 5/18/2011 330
It will give the same result based on date of birth...
~ Praveen
-
Merge multiple columns into a single column?
Hello
I need to perform queries dynamically and the return values. I need to retrieve the values of the queries in a single column only by concatenating multiple columns. I can't use the PL/SQL in my scenario.
is it possible to run a query and the result will be extracted in a single column (multiple column values must be concatenated)?
Thank you
Raja.SELECT rtrim(extract(xmltype(REPLACE(column_value,''',',')),'/ROW/*/text()'),',') col FROM TABLE (SELECT xmlsequence(dbms_xmlgen.getxmltype('select * from employees').extract('ROWSET/ROW')) FROM dual );
Check this box... Copy it directly to this
Ravi Kumar
-
Concatenate multiple columns in a single string
Hello
I use Oracle 11.2, how can I concatenate values from multiple columns in a string with an SQL:
create table testTb (number (5) classId, class varchar2 (32));
Insert into the testTb value (101, 'room101');
Insert into the testTb value (101, 'room201');
Insert into the testTb value (101, 'room301');
Insert into the testTb value (202, 'room444');
Insert into the testTb value (202, 'room555');
I would like to generate the result as following:
Class 101 is room101, room201, room301
202 class is located in room444, room555
Thank youPlease post sample data.
11.2 you can use LISTAGG:SQL> select 'Class '||classid||' is in '||listagg(classroom, ', ') within group (order by classroom) str 2 from testtb 3 group by classid; STR -------------------------------------------------------------------------------- Class 101 is in room101, room201, room301 Class 202 is in room444, room555 2 rows selected. SQL>
-
Select multiple columns into a single column group
SQL dear Experts,
I have a question related to pl/sql.
I do query below. Please advice in right way.
Select phone, firstname, lastname code
of the customer
Code group
Group, but in the meantime, firstname and lastname.
Please advice
Thank you
AngeliqueBilly wrote:
I have a question related to pl/sql.
You posted the SQL code. Not PL/SQL code.
I do query below. Please advice in right way.
Select phone, firstname, lastname code
of the customer
Code groupGroup, but in the meantime, firstname and lastname.
Of course, you will also need to group by firstname and lastname for this SQL query.
With a Group of SQL, you have basically 2 types of values that can be returned:
-the value of Group of
-l' aggregated/calculated the value of this groupIf you could watch the first name and the last name by code:
select code, MIN(firstname), MAX(lastname) from customer group by code
You can see the number of unique name and surname by code:
select code, COUNT(DISTINCT firstname), COUNT(DISTINCT lastname) from customer group by code
Think of the clause group by in size (for example the code in the SQL above) and measures (calculations by code in the SQL above).
-
Use cursor Fetch to return multiple columns of data
Hello
This is my Table:
SQL > select * connection;
USERNAME PASSWORD CONFIRMPASSWORD
--------------- --------------- ---------------
Happy SAI SAI
Kiran keyboard keyboard
JAINA JAINA VARNU
It's my stored procedure for this Table, it works very well there, Fetch it has the cursor returns only a single column of data.
CREATE OR REPLACE PROCEDURE getEmpName (EMP_ID IN VARCHAR2)
IS
EMPNAME VARCHAR2 (50);
CURSOR MYCUR
IS
SELECT a connection username where USERNAME = EMP_ID;
BEGIN
MYCUR OPEN;
LOOP
EXTRACT MYCUR IN EMPNAME;
DBMS_OUTPUT. PUT_LINE (EMPNAME);
WHEN THE OUTPUT MYCUR % NOTFOUND;
END LOOP;
close MYCUR;
END;
Now, I have a requirement, I need to get the password also with user name,
Please tell me how to use FETCH from cursor to fill in the details in the declared Variables
EXTRACT MYCUR IN EMPNAME;
CREATE OR REPLACE PROCEDURE getEmpName (EMP_ID IN VARCHAR2)
IS
EMPNAME VARCHAR2 (50);
VARCHAR2 (50) PASSWORD.
CURSOR MYCUR
IS
SELECT username, PASSWORD of connection where USERNAME = EMP_ID;
BEGIN
MYCUR OPEN;
LOOP
FETCH IN EMPNAME MYCUR; / / Need help here *.
DBMS_OUTPUT. PUT_LINE (EMPNAME);
WHEN THE OUTPUT MYCUR % NOTFOUND;
END LOOP;
close MYCUR;
END;
Published by: user10503747 on October 14, 2010 11:51
Published by: user10503747 on October 14, 2010 11:52EXTRACT MYCUR IN EMPNAME, PASSWORD;
SY.
-
SQL multiple columns in a single row
Hi all
I have 2 tables, product and Product_Name, a product can have several names.
I need to recover what I show the Product_ID followed by all the names of this product has.
I am not able to do, every way I try get the product ID duplicated several lines with a name of different product on each line as follows:
' 1, ' iron Z.
1, "iron M.
1, "iron N".
2, 'wood P.
2, 'wood M.
What I need is:
1, Z, M iron, iron N
2, wood P, wood M
Thank you and best regards.Hello
user10103934 wrote:
Thanks for the reply from Frank,Iron Z, iron and iron N M would be 3 different entries in the same column.
I'm sure that the LISTAGG function should solve this problem, the problem is that I expected to find a solution on pure SQL or PL/SQL, perhaps with a nested Select statement.
My version of Oracle's 10g Express Edition.
LISTAGG is pure SQL, but it was introduced only in Oracle 11.2. All mentioned below should work in Oracle 10.
The STRAGG from this page is very useful. You must copy and install approximately 60 line of PL/SQL code. Do it once, and then you can use hundreds of times in hundreds of motions, as if it were a built-in function. The main problem with STRAGG, it is difficult to get the output soprted. There is a modified version, designed for output sorted on this thread:
http://asktom.Oracle.com/pls/asktom/f?p=100:11:0:P11_QUESTION_ID:15637744429336
Never used. Can't vouch for it.SYS_CONNECT_BY_PATH seems to be the most popular way after the aggregation of the chain in Oracle 10. The example given on the page of the Oracle Base (that I posted in my last post) is a little clumsy and inefficient. See the next thread for a better example, using CONNECT_BY_ISLEAF:
Re: Concatenate strings more lines in a single line.
or, now that I see it, Pollywog example above.Published by: Frank Kulash, June 11, 2010 14:24
-
Multiple queries in a single request
Dear Experts
In my application, I have four running queries which produces TRUE or FALSE, I want to do all these four motions in a single SQL QUERY and return TRUE or FALSE
create table customer
(
number of cust_id,
Number of Enrol_number
acc_num varchar2 (20).
acc_num_1 varchar2 (20).
e-mail varchar2 (20).
param_id varchar2 (20).
number of reg_id
VARCHAR2 (20) mobile
);
insert into customer values (101,5001,851276914587912,563214785369851,' [email protected]' 01, 45, "1234567890");
insert into customer values (102,5002,851276914587900,563214785369800,' [email protected]'02, 46, ' 1234567800');
insert into customer values (103,5003,851276914587901,563214785369700,' [email protected]'03 47, ' 1234567500');
Here are my four queries
Select cust_id as holders of the customer
where cust_id = 102 and Enrol_number <>5001 - returns true
Select cust_id as the name of
client where
(acc_num = 851276914587912 or acc_num_1 = 563214785369851)
and Enrol_number <>5002 - returns true
Select cust_id as places of
client where reg_id = 45 and param_id = 01
and UPPER (email) ='[email protected] ' and Enrol_number <>5001; -Returns false because the conditions are not met
Select cust_id as fourthlevel of
client where reg_id = 45 and param_id = 01
and mobile = 1234567890 and Enrol_number <>5001 - returns false because the conditions are not met
Output of desire
------------------------
Bringing together disbarred Thirdlevel Fourthlevel
TRUE FALSE FALSE TRUE
I don't want a customer Id if poster, here we have to given to verify
Help, please
Dear Ricky007, if I could help you please mark as helpful or correct answer
SELECT
(SELECT
CASE
WHEN COUNT (CUST_ID) = 1 THEN 'TRUE '.
WHEN COUNT (CUST_ID) = 0 THEN 'FALSE. '
END AS BRINGING TOGETHER
OF ZCUSTOMER
WHERE CUST_ID = 102
AND ENROL_NUMBER <> 5001) bringing TOGETHER.
(SELECT CASE
WHEN COUNT (CUST_ID) = 1 THEN 'TRUE '.
WHEN COUNT (CUST_ID) = 0 THEN 'FALSE. '
END DISBARRED ACE
OF ZCUSTOMER
WHERE (ACC_NUM = 851276914587912 OR ACC_NUM_1 = 563214785369851)
AND ENROL_NUMBER <> 5002) REMOVED.
(SELECT CASE
WHEN COUNT (CUST_ID) = 1 THEN 'TRUE '.
WHEN COUNT (CUST_ID) = 0 THEN 'FALSE. '
END AS PLACES
OF ZCUSTOMER
WHERE REG_ID = 45
AND PARAM_ID = 01
AND UPPER (EMAIL) = ' [email protected]'
AND ENROL_NUMBER <> 5001) PLACES.
(SELECT CASE
WHEN COUNT (CUST_ID) = 1 THEN 'TRUE '.
WHEN COUNT (CUST_ID) = 0 THEN 'FALSE. '
END AS FOURTHLEVEL
OF ZCUSTOMER
WHERE REG_ID = 45
AND PARAM_ID = 01
AND MOBILE = 1234567890
AND ENROL_NUMBER <> 5001) FOURTHLEVEL
DOUBLE;
-
Update multiple columns from multiple tables in a single UPDATE request
Hello
I'm trying to figure if I'm heading in the right direction.
I want to update multiple columns from multiple tables in a single UPDATE request. Also, I would like to update multiple columns in a table from the tables.
Scenario 1
UPDATE Table2, Table 3 SET T2.Column1 = T1.Column1 ,T2.Column2 = T1.Column2 ,T3.Column2 = T1.Column2 FROM Table1 T1, Table2 T2, Table3 T3 WHERE T1.id = T2.id and T1.id = T3.id
Scenario 2
UPDATE Table3 SET T3.Column1 = T1.Column1 T3.Column2 = T1.Column2 ,T3.Column3 = T2.Column3 ,T3.Column4 = T2.Column4 FROM Table1 T1, Table2 T2, Table3 T3 WHERE T3.id = T1.id and T3.id = T2.id
Hello
For scenario 1, you must write separate instructions UPDATE table2 and table3.
To guard against someone else change one of these tables while you act so you can copy all relevant data in a global temporary table and update this global temporary table table3.
ENGAGE only when two tables have been changed.
You can write a procedure or an INSTEAD OF trigger to do all this.
For scenario 2, you can reference many tables that you need when new table3. It might be more efficient and simpler to use the MERGER rather than UPDATED. For example:
MERGE INTO table3 dst
WITH THE HELP OF)
SELECT t1.id
t1.column1
t1.column2
t2.column3
t2.column4
FROM table1 t1
JOIN table2 t2 ON t1.id = t2.id
) src
WE (dst.id = src_id
WHEN MATCHED THEN UPDATE
SET dst.column1 = src.column1
dst.column2 = src.column2,
dst.column3 = src.column3,
dst.column4 = src.column4,
;
-
single line sub query returns multiple rows
Hi, please help me to solve this, working with oracle 11g.
Update t1 set t1.twyindex = twypoly (select twyindex from twyinfo where t1.id = t2.id t2);
the error message is:
*
ERROR on line 1:
ORA-01427: einreihig subquery returns multiple rows
Thank youdon123 wrote:
Hi paul, thanks...duplicate existing due to the business logic data.
can I use the SQL mentioned above for all cases?
is it mandatory to remove duplicates?
Please provide your suggestions...
If the company says duplicates are allowed, you have to ask the person who wants what, of the different twyindexes, that they want to use
updating twyinfo table...I use the SQL proposed until they tell you that twyindex to use.
-
Return multiple values from a function in a SELECT statement
I hope I've provided enough information here. If not, let me know what I'm missing.
I create a view that will combine the information from several tables. Most are pretty simple, but there are a couple of columns in the view that I need to get by running a function within a package. Even if this is quite simple (I have a function named action_date in a package called rp, for example, that I can use to return the date that I need through SOME rp.action_date (sequence_number).
Here is the question: I really need to return several bits of information of the same record (not only action_date, but also action_office, action_value, etc.)-a join of the tables will work not here, as I will explain below. I can, of course, perform a function separate for each statement, but this is obviously inefficient. Within the select statement of the view, however, I don't know how each of the values that I need to get back.
For example, right now, I have:
Table 1:
sequence_number NUMBER (10),
name varchar (30),
...
Table2:
Table1_seq NUMBER (10),
action_seq NUMBER (10),
action_date DATE,
action_office VARCHAR (3),
action_value VARCHAR (60),
...
I can't just simply join Table1 and Table2 because I have to perform processing in order to determine the rows returned matching, I really need to select. If the package opens a cursor and treats each line until it finds the one I need.
The following works but is ineffective since all calls to the package returns the columns of the same record. I don't know how to put all the values that I need in the SELECT statement.
CREATE VIEW all_this_stuff AS
SELECT sequence_number, name,
RP.action_date (sequence_number) action_date,
RP.action_office (sequence_number) action_office,
RP.action_value (sequence_number) action_value
FROM table1
Is there a way to return multiple values in my SELECT statement or I'm going about this all wrong?
Any suggestions?
Thank you very much!Hello
What you want is a Query of Top - N , what you can do using the ROW_NUMBER analytic function in a subquery, like this:
WITH got_rnum AS ( SELECT action_seq, action_dt, action_office, action_type, action_value , ROW_NUMBER () OVER ( ORDER BY action_date , action_seq , action_serial ) AS rnum FROM table2 WHERE action_code = 'AB' AND action_office LIKE 'E' -- Is this right? ) SELECT action_seq, action_dt, action_office, action_type, action_value FROM got_rnum WHERE rnum = 1 ;
As written, this returns a single line (at most).
I suspect you'll actually get a rank for each group , where a group is defined by a value in a table in which you join.
In this case, add a PARTITION BY clause to the ROW_NUMBER function.
If post you a small example of data (CREATE TABLE and INSERT statements), I could show you exactly how.
As I don't have your tables, I'll show you the use of the tables in the scott schema.
This is a view containing data in the scott.dept table and also to scott.emp, but only for the highest employee in each Department (in other words, the employee whose oldest hire date). If there be a tie for the first hire date, while the candidate with the lowest empno is selected.CREATE OR REPLACE VIEW senior_emp AS WITH got_rnum AS ( SELECT d.deptno , d.dname , e.empno , e.ename , e.hiredate , ROW_NUMBER () OVER ( PARTITION BY d.deptno ORDER BY e.hiredate , e.empno ) AS rnum FROM scott.dept d JOIN scott.emp e ON d.deptno = e.deptno ) SELECT deptno , dname , empno , ename , hiredate FROM got_rnum WHERE rnum = 1 ; SELECT * FROM senior_emp ;
Output:
. DEPTNO DNAME EMPNO ENAME HIREDATE ---------- -------------- ---------- ---------- --------- 10 ACCOUNTING 7782 CLARK 09-JUN-81 20 RESEARCH 7369 SMITH 17-DEC-80 30 SALES 7499 ALLEN 20-FEB-81
Moreover, one of the conditions to the query you posted has been
action_office LIKE 'E'
which equals
action_office = 'E'
(AS is always equivalent to = if the string that follows AS does not contain the winning cards.)
Did you mean say that or did you mean something like this:action_office LIKE 'E%'
Instead?
-
Help in the treatment of "subquery returns multiple rows.
Appreciate your help on this.
I have under sql query fails with the error "ORA-01427: einreihig subquery returns multiple lines"
WITH t AS (SELECT 'A' Col1, 'B' Col2, 'C' Col3 FROM DUAL UNION SELECT 'D', 'E', 'F' FROM DUAL UNION SELECT 'E', 'F', 'G' FROM DUAL UNION SELECT 'A', 'T', 'U' FROM DUAL), t1 AS (SELECT 'A' Col1, 'B' Col2, 'C' Col3 FROM DUAL UNION SELECT 'D1', 'E1', 'F1' FROM DUAL UNION SELECT 'D', 'E', 'F' FROM DUAL UNION SELECT 'S', 'V', 'W' FROM DUAL), t2 AS (SELECT 'A' Col1, 'B' Col2, 'C' Col3 FROM DUAL UNION SELECT 'A', 'E1', 'F1' FROM DUAL UNION SELECT 'D', 'E', 'F' FROM DUAL) SELECT t.col1, (SELECT distinct col2 FROM t2 WHERE t2.col1 = t.col1) RND_COL FROM t, t1 WHERE t.col1 = t1.col1 WhenI checked the count using below query WITH t AS (SELECT 'A' Col1, 'B' Col2, 'C' Col3 FROM DUAL UNION SELECT 'D', 'E', 'F' FROM DUAL UNION SELECT 'E', 'F', 'G' FROM DUAL UNION SELECT 'A', 'T', 'U' FROM DUAL), t1 AS (SELECT 'A' Col1, 'B' Col2, 'C' Col3 FROM DUAL UNION SELECT 'D1', 'E1', 'F1' FROM DUAL UNION SELECT 'D', 'E', 'F' FROM DUAL UNION SELECT 'S', 'V', 'W' FROM DUAL), t2 AS (SELECT 'A' Col1, 'B' Col2, 'C' Col3 FROM DUAL UNION SELECT 'A', 'E1', 'F1' FROM DUAL UNION SELECT 'D', 'E', 'F' FROM DUAL) SELECT t.col1, (SELECT count(col2) FROM t2 WHERE t2.col1 = t.col1) RND_COL FROM t, t1 WHERE t.col1 = t1.col1 (+) it shows as below ----------------- COL1 RND_COL A 2 A 2 D 1 E 0 My Requirement is for all the values in the column 'RND_COL' > 1 it should display text as 'Multiple', for 'RND_COL' = 1 display actual value returned by sub query and 'RND_COL' = 0 display it as NULL. expected output ------------------- COL1 RND_COL A Multiple A Multiple D E E NULL
Hello
Here's another way. It's like the solution in response #1, but it does not use a subquery:
SELECT t.col1
CASE
WHEN COUNT (DISTINCT t2.col2) > 1
THEN "Multiple."
For ANOTHER MIN (t2.col2)
END AS rnd_col
T
LEFT OUTER JOIN t2 ON t2.col1 = t.col1
GROUP OF t.col1, t.col2, t.col3
ORDER BY t.col1
;
This assumes that in table t (col1, col2, col3) combination is unique. If theat is not the case, change the GROUP BY clause, but you need to ensure that all lines of t becomes a separate group.
-
HP Envy printer 4501: HP Envy 4501 scan multiple pages into a single document
My HP Envy 4501 printer won't let me not scan multiple pages into a single pdf document.
I already made sure the box 'Create a separate file for each scanned page' is unchecked under the section of the file in the advanced settings .
After I scan the first page, I do not get a screen with a + (plus sign) which is supposed to allow you to scan additional pages in the same document.
Is it possible that I can get a fix/update my HP Envy 4501 printer software which would show the screen with the + (plus sign) which allows to scan additional pages in the same document after the first page that you scanned?
At this point, if I don't get this problem fixed soon, I'm about to return my HP Envy 4501 printer to the store I bought so I can get my money back and buy a printer from one of the competitors of HP before my store warranty runs out.
I am very displeased with the printing software HP, support services and web presence that does not work half the time.
Thank you
Mark
Hello
Lower the resolution of scan equal or lower to 300 DPI, scanning multiple pages is supported only on lower resolutions.
Any higher resolution will not add additional pages.
Shlomi
-
Return multiple values at once of the listOfValues region
Friends,
I created a (listOfValues) region that has 4 fields/columns
ResponsibilityName, ResponsibilityId, ApplicationName, ApplicationId
I assigned a responsibility field ResponsibilityName of the listOfValues in a page.
It works fine when I select a value in this LOV. It returns a value to the field of 'Responsibility' of the page.
Is it possible to return the other 3 fields so while selecting ResponsibilityName in LOV. for example while you select a value for the field 'Responsibility', can the LOV return ResponsibilityId LOV to the 'ResponsibilityId' field in the page, at the same time?
1 selection can return values 1 to the fields?You can return multiple values in the LOV. Simply create a result to the mapping of the array element Lov to the basic element of page. Once you select a value from the LOV, the element of basic page could get filled in with the value on the table of lov whereby it has been mapped.
Concerning
Sumit -
concatenate the strings from a column into a single row?
How to concatenate strings from a column into a single line?
Color
------
Red
Orange
Blue
Green
And return a set of results as follows:
Colors
-------------------------
Red, orange, blue, greenVarious ways can be found here:
http://www.Oracle-base.com/articles/10G/StringAggregationTechniques.php
Maybe you are looking for
-
MousePoint Cape 4100XCDT part number
Someone at - it a reference number of the MousePoint CAP for this 4100xcdt?The size is square stick switch size is smaller than the other Toshibas about 2-3 mm from each side as opposed to 4-5 mm for others.I came across the P000257680 part number, b
-
How to generate a pulse signal?
Hello I'm relatively new to LabVIEW and I need to generate an impulse (Dirac function) in the motor continuous. At the same time, I need to be able to change the pulse width. I am currently using LabVIEW 7.1.
-
I'm trying to reinstall Windows Vista with DVD. The DVD is not being perceived or playback after inserting into the DVD recorder. Another DVD or CD that I insert in the CD/DVD burner drive can be read and accessed. Only disks Vista DVD cannot be read
-
Report of Junk coming out Good Versus messed up because of policy filter
Hello We currently have a policy filter for outgoing mails that add some sort of warning. Addition of the warning itself works flawless, but statistics is screwed up because all outgoing mail is classified as a threat 'Policy' and considered to be un
-
BlackBerry Q10 need help with the input language
I went to setting and setting 'English' and 'Chinese' as my input language. However, when I'm really typing in text or wtsapp. I don't know how to switch from English to Chinese. I searched the help sections and just mention how to add the input lang