Query to get a unique row
Hi,
SELECT main_grp_name,category,sub_category,commodity_name
FROM category_list
WHERE main_grp_name IN(
SELECT main_grp_name
FROM category_list
GROUP BY main_grp_name
HAVING COUNT (distinct category)<=3 )
This is a query which should give me unique main_grp_name and category..
For a main_grp_name there can be three category name or less but it should be unique... But now I hve a case where there are two rows with same main_grp_name and same category_name.. In this case I should look for sub_category and based on that I should pick up only one row
eg: the query returns the following
MAIN_GRP_NAME CATEGORY SUB_CATEGORY COMMODITY_NAME
MEDICINE whole_sale Trauma ABC
MEDICINE whole_sale Anxiety SYX
MEDICINE retail Trauma SSS
MEDICINE mail Anti_psy GGG
Here I should get only one out of first two rows as I am considering only MAIN_GRP_NAME and CATEGORY as the criteria.
If I have two rows with same value for these fields then I should look for SUB_CATEGORY and select the row with VALUE 'ANXIETY'
eventually I should have only
MEDICINE whole_sale Anxiety SYX
MEDICINE retail Trauma SSS
MEDICINE mail Anti_psy GGG
Anybody please help
regards
SQL> WITH t AS
2 (SELECT 'MEDICINE' main_grp_name, 'whole_sale' CATEGORY,
3 'Trauma' sub_category, 'ABC' commodity_name
4 FROM DUAL
5 UNION ALL
6 SELECT 'MEDICINE', 'whole_sale', 'Anxiety', 'SYX'
7 FROM DUAL
8 UNION ALL
9 SELECT 'MEDICINE', 'retail', 'Trauma', 'SSS'
10 FROM DUAL
11 UNION ALL
12 SELECT 'MEDICINE', 'mail', 'Anti_psy', 'GGG'
13 FROM DUAL)
14 SELECT main_grp_name, CATEGORY, sub_category, commodity_name
15 FROM (SELECT t.*,
16 ROW_NUMBER () OVER (PARTITION BY main_grp_name, CATEGORY ORDER BY sub_category)
17 rn
18 FROM t)
19 WHERE rn = 1;
MAIN_GRP CATEGORY SUB_CATE COM
MEDICINE mail Anti_psy GGG
MEDICINE retail Trauma SSS
MEDICINE whole_sale Anxiety SYX
SQL> Edited by: Salim Chelabi on 2009-02-12 09:57
Similar Messages
-
How to get a unique row in a value set
How to get a unique row in a value set which is used in concurrent program.
Example if a table contains 10 unique rows i need only one row to show.
Thanksadd conditions in where clause to supress the duplicate values.
On how to supress the duplicate values follow the link
http://oracleschools.com/index.php?topic=40.msg76#msg76
Thanks
Prudhvi
www.erpschools.com -
Selecting unique rows in ADF ViewObject
Hi,
In my ADF application, i am fetching data from a table. the situation is, my table is having same row of data multiple times. The primary key is a sequence. I want to fetch distinct rows of data from the table.
So, I wrote query to fetch the distinct rows of the table.
The query works in the Database SQL worksheet, but when i use it in my ViewObject and run, it throws an error saying
View object ActiveUsersVO does not include a primary key attribute Pk of entity base ExtUserMapping.here Pk is my primary key. I did not used it in the query to get the unique rows.
help me fetch the unique rows in ADF without the primary key
thanks,
RajanUser please tell us yor jdev version!
This should be no problem as long as your VO is build as road only based on a query like
select distinct department_id from job_historyThis VO can be used without a PK, however some function which are working on PKs won't work. The query works on hte HR schema.
Timo -
Getting number of rows in a resultset
I am moving my application from JDBC 1.0 to JDBC 2.0. In JDBC 1.0, I used to fire separate query for count(*) to get the no. of rows in results but with JDBC 2.0 is there way that I dont need to execute a separte query to get no. or rows in a resultset.
Thanks
SushilThere is Sushil if your driver supports it. It can be done with scrollable ResultSets.
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery("sql");
if (rs != null) {
rs.last();
int numRows = rs.getRow();
// be sure to set rs.beforeFirst() if you want to process the ResultSet
} -
SSRS report with cube – MDX query how to get an extra row with value '0'.
Hello everyone,
I'm unable to write the MDX query to get '0' value as first row in output. Following is my MDX query:
WITH MEMBER [Measures].[Dummy] AS '0'
SELECT NON EMPTY Union( {[Measures].[Amount] },{[Measures].[Dummy]}) ON COLUMNS,
NON EMPTY { ([Customer].[Customer Nbr].[Customer Nbr].ALLMEMBERS * [Fiscal].[Year].[Year].ALLMEMBERS ) }
having [Measures].[Amount] > 5000
ON ROWS FROM [cube]
With above query, the output returns the value '0' as a separate column.
I would like to get it in form of first row for [Measures].[Amount]. Like,
Amount
0
500
200
100
What needs to be changed to achieve the above result? I'm planning to use the above value in line chart to start the line from 0th value as described in following URL. (Note: The below URL is using SQL query and not MDX expressions.)
http://spinerain.blogspot.in/2013/09/ssrs-line-chart-create-stacked-line-and.html
Thanks, Ankit Shah
Inkey Solutions, India.
Microsoft Certified Business Management Solutions Professionals
http://www.inkeysolutions.com/MicrosoftDynamicsCRM.htmlThe round brackets in your expression are forcing an implicit crossjoin between the 3 lines. I would do the following which creates a set of the DummyYear plus the real year members and then crossjoin that with the customer set.
WITH MEMBER [Fiscal].[Year].DummyYear AS '0'
SELECT NON EMPTY {[Measures].[Amount]} ON COLUMNS,
NON EMPTY {[Fiscal].[Year].DummyYear,
[Fiscal].[Year].[Year].MEMBERS} *
[Customer].[Customer Nbr].[Customer Nbr].MEMBERS
having [Measures].[Amount] > 5000
ON ROWS FROM [cube]
http://darren.gosbell.com - please mark correct answers -
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. -
Query for how to display unique rows in a table
Can i have a query for displaying unique rows in a table.
use d query
select distinct col1,col2... from table ; -
Need a sql query to get multiple dates in rows
Hi All,
i need a query to get dates for last 7 days and each dates should be in one row...
but select sysdate from dual..gives one row...
Expexcted Output
Dates:
01-oct-2013
30-sep-2013
29-sep-2013
28-sep-2013
27-sep-2013
26-sep-2013Hi,
Do you mean that you want all 7 dates together on 1 row?
Here's one way:
SELECT LISTAGG ( TO_CHAR ( SYSDATE + 1 - LEVEL
, 'DD-Mon-YYYY'
) WITHIN GROUP (ORDER BY LEVEL) AS txt
FROM dual
CONNECT BY LEVEL <= 7
This is an example of String Aggregation, that is, taking a column on multiple rows, and concatenating all the values (however many htere happen to be) into 1 big string column 1 row.
Like everything else, exactly how to do it depends on your Oracle version.
For more on String Aggregation, including differetn techniques for different versions, see http://www.oracle-base.com/articles/10g/StringAggregationTechniques.php
Message was edited by: FrankKulash
Sorry, I mis-read the question. -
SQL query - return single unique rows
Hi
If you have an employee table where employees are listed per department, using SQL, how could you return the names of the employees listed per department on a single unique row?
Eg - select deptno, first_name from employee
deptno first_name
10 Jane
20 Jack
10 Joe
20 Jill
10 Jacinta
30 John
30 Jeffrey
10 Jackie
30 Jennifer
... etc.
the return set of the query would look like:
deptno first_name concat
10 Jane Joe Jacinta Jackie ..
20 Jack Jill ..
30 John Jeffrey Jennifer ..
CheersHere you go:
WITH t AS
(SELECT 10 deptno, 'Jane' first_name FROM dual UNION
SELECT 20 deptno, 'Jack' first_name FROM dual UNION
SELECT 10 deptno, 'Joe' first_name FROM dual UNION
SELECT 20 deptno, 'Jill' first_name FROM dual UNION
SELECT 10 deptno, 'Jacinta' first_name FROM dual UNION
SELECT 30 deptno, 'John' first_name FROM dual UNION
SELECT 30 deptno, 'Jeffrey' first_name FROM dual UNION
SELECT 10 deptno, 'Jackie' first_name FROM dual UNION
SELECT 30 deptno, 'Jennifer' first_name FROM dual)
SELECT deptno,
RTRIM(XMLAGG(XMLELEMENT(c, first_name||' ') ).EXTRACT ('//text()'), ' ') names
FROM t
GROUP BY deptno -
Multi Row Delete and then I get a unique contraint violation on my PK
I have a simple table with 2 columns, one a PK. I have a checkbox style, multi-row delete function setup on this (to be honest, APEX set this up automatically).
I removed the add/edit functionality to keep just the delete button and delete procedure.
When I select an item, and then click delete, I get a unique constraint violation that I'm violating my Primary Key.
How can I fix this, or see what it's doing when it tries to delete the row?Hi,
It sounds as though you haven't properly removed all of the add/edit functionality or that you still have some form of validation and/or computation in place or that you have a trigger that is trying to insert records into, for example, a history table (is the constraint on the table you are deleting from - the error message should tell you this?)
Check that the only process you have is ApplyMRD and that this is pointing to the correct table and has the correct primary key set. Ensure that this has Conditional Processing set for a Request of "MULTI_ROW_DELETE".
Check for any validations - there is no need to perform validations if your user can not insert or update data unless you want to check that they've ticked one or more checkboxes.
Check for processes that could run if the user clicks the Delete button. Validations and processes could be conditional on either the button click or on request = "MULTI_ROW_DELETE".
Review any triggers that you have on the table to ensure that deletions do not try to insert records into another table where the primary key on that table is not being populated.
Regards
Andy -
How to modify the query to get the output in a single row
Hi All,
Below is the query i have written it works fine
select DISTINCT right(left(CTACCT,13),4) AS LocationNum,
tODS_GLBalance.FiscalYearId AS FiscalYearId,
tODS_GLBalance.FiscalMonthOfYearId AS FiscalMonthOfYearId,
--tods_GLMetadata.Metric,
Case when
tods_GLMetadata.Metric = 'Gross Margin'
Then SUM(Balance)
Else 0
END AS GrossMargin,
Case when
tods_GLMetadata.Metric = 'Occupancy'
Then SUM(Balance)
Else 0
END AS Occupancy,
Case when
tods_GLMetadata.Metric = 'Payroll Dollars'
Then SUM(Balance)
Else 0
END AS Payroll,
Case when
tods_GLMetadata.Metric = 'CF Sales'
Then SUM(Balance)
Else 0
END AS OperatingSales,
Case when
tods_GLMetadata.Metric = 'Operations'
Then SUM(Balance)
Else 0
END AS OperatingExpenses
-- 0 as payroll
from ods.[JJill].[tODS_GLBalance]
inner join ods.Staging.tODS_INF_GLPCT ON tODS_GLBalance.PageNum = tODS_INF_GLPCT.CTPAGE
inner join ods.JJill.tods_GLMetadata ON tods_GLMetadata.AcctDescription = tODS_INF_GLPCT.CTDESC
where
(tODS_GLBalance.FiscalYearId = 2012) and
(tODS_GLBalance.FiscalMonthOfYearId = 2) and
(right(left(CTACCT,13),4)= 3020)
group by
right(left(CTACCT,13),4),
tODS_GLBalance.FiscalYearId,
tODS_GLBalance.FiscalMonthOfYearId,
tods_GLMetadata.Metric
This is the sample output,
LocationNum FiscalYearId FiscalMonthOfYearId GrossMargin Occupancy Payroll OperatingSales OperatingExpenses
3020 2012 2 -112477.00 0.00 0.00 0.00 0.00
3020 2012 2 0.00 0.00 0.00 -158288.94 0.00
3020 2012 2 0.00 0.00 0.00 0.00 5625.44
3020 2012 2 0.00 0.00 24185.79 0.00 0.00
3020 2012 2 0.00 31075.53 0.00 0.00 0.00
But, i am expecting the output to be something like this
LocationNum FiscalYearId FiscalMonthOfYearId GrossMargin Occupancy Payroll OperatingSales OperatingExpenses
3020 2012 2 -112477.00 31075.53 24185.79 -158288.94 5625.44
Can someone please help me with changing my query to get the desired output?
Please let me know if you have any questions.
ThanksTry this:
SELECT DISTINCT
RIGHT(LEFT(CTACCT,13),4) AS LocationNum, tODS_GLBalance.FiscalYearId AS FiscalYearId, tODS_GLBalance.FiscalMonthOfYearId AS FiscalMonthOfYearId,
SUM(CASE WHEN tods_GLMetadata.Metric = 'Gross Margin' THEN Balance ELSE 0 END ) AS GrossMargin,
SUM(CASE WHEN tods_GLMetadata.Metric = 'Occupancy' THEN Balance ELSE 0 END ) AS Occupancy,
SUM(CASE WHEN tods_GLMetadata.Metric = 'Payroll Dollars' THEN Balance ELSE 0 END ) AS Payroll,
SUM(CASE WHEN tods_GLMetadata.Metric = 'CF Sales' THEN Balance ELSE 0 END ) AS OperatingSales,
SUM(CASE WHEN tods_GLMetadata.Metric = 'Operations' THEN Balance ELSE 0 END ) AS OperatingExpenses
FROM ods.[JJill].[tODS_GLBalance]
INNER JOIN ods.Staging.tODS_INF_GLPCT
ON tODS_GLBalance.PageNum = tODS_INF_GLPCT.CTPAGE
INNER JOIN ods.JJill.tods_GLMetadata
ON tods_GLMetadata.AcctDescription = tODS_INF_GLPCT.CTDESC
WHERE tODS_GLBalance.FiscalYearId = 2012
AND tODS_GLBalance.FiscalMonthOfYearId = 2
AND RIGHT(LEFT(CTACCT,13),4) = 3020
GROUP BY right(left(CTACCT,13),4), tODS_GLBalance.FiscalYearId, tODS_GLBalance.FiscalMonthOfYearId, tods_GLMetadata.Metric -
How to write a query to get the total as a last row
Hi,
I need to get something like this ....
|TEAM LEADER| TEAM | OCT TRN | EMPS| YTD% |
|_____________|__________|__________|______|_______|
| JOHN | JD Team | 12 | 12 | 100 |
|_____________|__________|__________|______|_______|
| Total | | 12 | 12 | 100 |
|_____________|__________|__________|______|_______|
I have to get the last row as total adding the number columns ...
Thanks in advance ...Take a look at the GROUP BY ROLLUP feature:
create table t1
(team_name varchar2(30)
,wins number
,losses number
insert into t1 values ('Hornets',3,1);
insert into t1 values ('Panthers',4,0);
insert into t1 values ('Wolves',2,2);
insert into t1 values ('Badgers',0,4);
insert into t1 values ('Hornets',1,3);
commit;
select decode(team_name,
NULL,'TOTAL',
team_name) team_name, sum(wins), sum(losses)
from t1
group by rollup(team_name);
TEAM_NAME SUM(WINS) SUM(LOSSES)
Badgers 0 4
Hornets 4 4
Panthers 4 0
Wolves 2 2
TOTAL 10 10 -
Single Sub Row Query Returns More Than 1 Row!
I am trying to update values in a table from another table and getting the error: Single Sub Row Query Returns More Than 1 Row.
I want table B's PRV_NAME updated into table A's PRV_NAME where A.PRVID = B.PRVID where B.PRV_TYPE = M'
Both tables have all unique PRVID's, however, table B has PRVID's that have the same name. So table B data can look like this:
PRVID PRV_NAME
1234 PHOENIX MED
1235 SAC MED
1236 SAC MED
1237 OVERLAND
etc..
So, as you can see the PRVID's are unique, but not the PRV_NAME's. Is this the reason why I get this error?
I did not build the tables and have no control over what is put in them. If this is the reason for the error, is there any way to resolve this?
For reference, here is the query. Maybe there is something wrong with this?
update msb_prv_source ps
set ps.prv_name =
(select prv00.prv00_prv_name
from prv00_prv prv00
join msb_prv_source ps
on prv00.prv00_prv_id = ps.prvid
where prv00.prv00_prv_type = 'M')
Edited by: user12296489 on Apr 19, 2013 10:46 AMHi,
user12296489 wrote:
I am trying to update values in a table from another table and getting the error: Single Sub Row Query Returns More Than 1 Row. Post your code. It's hard to say what you're doing wrong when I don't know what you're doing.
I want table B's PRV_NAME updated into table A's PRV_NAME where A.PRVID = B.PRVID
Both tables have all unique PRVID's, however, table B has PRVID's that have the same name. So table B data can look like this:
PRVIDIf b.prvid is really unique, then
UPDATE a
SET prv_name = (
SELECT prv_name
FROM b
WHERE a.prvid = b.prvid
;should work, whether the other columns are unique or not.
(Depending on your data and your requirements, you might want to use MERGE rather than UPDATE).
I hope this answers your question.
If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all the tables involved, and the results you want from that data.
In the case of a DML operation (such as UPDATE) the sample data should show what the tables are like before the DML, and the results will be the contents of the changed table(s) after the DML.
Explain, using specific examples, how you get those results from that data.
Always say what version of Oracle you're using (e.g. 11.2.0.2.0).
See the forum FAQ {message:id=9360002}
Edited by: Frank Kulash on Apr 19, 2013 2:00 PM
I see you've posted your code now:
update msb_prv_source ps
set ps.prv_name =
(select prv00.prv00_prv_name
from prv00_prv prv00
join msb_prv_source ps
on prv00.prv00_prv_id = ps.prvid
where prv00.prv00_prv_type = 'M')Even if ps.prvid is unique, the sub-query can return more than 1 row if prv00.prv00_prv_id is not unique. When that that's the case, what do you want to happen? Include examples when you post the sample data and desired results. -
Query help : Query to get values SYSDATE-1 18:00 hrs to SYSDATE 08:00 hrs
Hi Team
I want the SQl query to get the data for the following comparison : -
Order Created is a Date Column , and i want to find out all the values from (SYSDATE-1) 18:00 hours to SYSDATE 08:00 hours
i.e.
(SYSDATE-1) 18:00:00 < Order.Created < SYSDATE 08:00:00.
RegardsHi, Rohit,
942281 wrote:
If i want the data in the below way i.e.
from (SYSDATE-1) 18:00 hours to SYSDATE 17:59 hours ---> (SYSDATE-1) 18:00:00 < Order.Created < SYSDATE 07:59:00.If you want to include rows from exactly 18:00:00 yesterday (but no earlier), and exclude rows from exatly 08:00:00 today (or later), then use:
WHERE ord_dtl.submit_dt >= TRUNC (SYSDATE) - (6 / 24)
AND ord_dtl.submit_dt < TRUNC (SYSDATE) + (8 / 24)
So can i use the below format : -
ord_dtl.submit_dt BETWEEN trunc(sysdate)-(6/24) and trunc(sysdate)+(7.59/24) . Please suggest . .59 hours is .59 * 60 * 60 = 2124 seconds (or .59 * 60 = 35.4 minutes), so the last time included in the range above is 07:35:24, not 07:59:59.
If you really, really want to use BETWEEN (which includes both end points), then you could do it with date arithmentic:
WHERE ord_dtl.submit_dt BETWEEN TRUNC (SYSDATE) - (6 / 24)
AND TRUNC (SYSDATE) + (8 / 24)
- (1 / (24 * 60 * 60))but it would be simpler and less error prone to use INTERVALs, as Karthick suggested earlier:
WHERE ord_dtl.submit_dt BETWEEN TRUNC (SYSDATE) - INTERVAL '6' HOUR
AND TRUNC (SYSDATE) + INTERVAL '8' HOUR
- INTERVAL '1' SECONDEdited by: Frank Kulash on Apr 17, 2013 9:36 AM
Edited by: Frank Kulash on Apr 17, 2013 11:56 AM
Changed "- (8 /24)" to "+ (8 /24)" in first code fragment (after Blushadown, below) -
Getting the first row for each group
Hi Everyone,
I have a query which returns a number of rows, all of which are valid. What I need to do is to get the first row for each group and work with those records.
For example ...
client flight startairport destairport stops
A fl123 LGW BKK 2
A fl124 LHR BKK 5
B fl432 LGW XYZ 7
B fl432 MAN ABC 8
.... etc.
I would need to return one row for Client A and one row for Client B (etc.) but find that I can't use the MIN function because it would return the MIN value for each column (i.e. mix up the rows). I also can use the rownum=1 because this would only return one row rather than one row per group (i.e. per client).
I have been investigating and most postings seem to say that it needs a second query to look up the first row for each grouping. This is a solution which would not really be practical because my query is already quite complex and incorporating duplicate subqueries would just make the whole thing much to cumbersome.
So what I really new is a "MIN by group" or a "TOP by group" or a "ROWNUM=1 by group" function.
Can anyone help me with this? I'm sure that there must be a command to handle this.
Regards and any thanks,
Alan Searle
Cologne, GermanySomething like this:
select *
from (
select table1.*
row_number() over (partition by col1, col2 order by col3, col4) rn
from table1
where rn = 1In the "partition by" clause you place what you normally would "group by".
In the "order by" clause you define which will have row_number = 1.
Edit:
PS. The [url http://download.oracle.com/docs/cd/E11882_01/server.112/e17118/functions004.htm#i81407]docs have more examples on using analytical functions ;-)
Edited by: Kim Berg Hansen on Sep 16, 2011 10:46 AM
Maybe you are looking for
-
Home sharing no longer working on one Mac
My wife and I used home sharing via my iTunes account without any problems about a year ago. Since then, we have both moved our iTunes libraries over to new Macs. Now, I can start home sharing on my Mac, but when I attempt to start home sharing on he
-
After upgrading to Mavericks, F14/F15 brightness adjustments don't work
After upgrading to Mavericks, F14/F15 brightness adjustments don't work. The screen appears to be "locked" at the dimmest brightness level. How do I adjust the brightness?
-
How to unlock Hp Desk top.
My daughter has forgotten the password for her HP Desktop model 120-1333W that she hasn't used since high school. I need to know how to unlock the computer or how to factory reset the computer so I can give it to her younger brother?
-
HT5649 I downloaded iTunes I can't get my iTunes short cut icon to load
I downloaded iTunes I can't get my iTunes short cut icon to load
-
Rep=2103 error message in oracle 10g
Hi After migrating from 6i to 10g I am getting the following msg when I try to generate a report: rep-2103: column 'cf_street_address' : pl/sql formula returned invalid value or no value I have the following code in my function: function CF_street_ad