Group By Select Top 1 Rows
Hi Guys,
I tried Group By from Select Top 1 Records, As below the script wasn't work.
Please help.
SELECT TOP 1 NR.SHGId, NR.Amount
FROM NEW_DCB_REPORT NR
WHERE NR.SHGId = ND.SHGId
AND NR.ShgMemberId = ND.ShgMemberId
AND NR.LoanNumber = ND.LoanNumber
GROUP BY NR.SHGId,NR.Amount
ORDER BY NR.LedgerNumber DESC
SHGId
SHGMemberId
LoanNumber
Amount
Select Top 1 Row
1028
147852
1
1000
Select Top 1 Row
1028
147853
1
2000
Select Top 1 Row
1028
147854
1
1000
Select Top 1 Row
1028
147855
1
1000
5000
I expected the results are:
SHGId
Amount
1028
5000
Yes I did it.
Select SHGId,
SUM(Amount)
amt FROM
SELECT NR.SHGId,
NR.Amount,
, Row_number()
Over(partition
by NR.SHGId,
NR.ShgMemberId , NR.LoanNumber
Order
by NR.LedgerNumber
DESC
) rn
FROM NEW_DCB_REPORT NR
JOIN
NEW_DCB_REPORT ND
ON
NR.SHGId
=
ND.SHGId
AND NR.ShgMemberId
= ND.ShgMemberId
AND NR.LoanNumber
= ND.LoanNumber
) t
Where rn=1
GROUP
BY SHGId
I just changed above the script Partition by add one more column and
[yourNDTable]
Should come NEW_DCB_REPORT table.
However, It shows below the error ,. Please help.
Invalid object name 'NEW_DCB_REPORT'.
Similar Messages
-
Selecting top row after sorting
hi,
i have a table emp, whose primary key is empid(varchar2),
i want to sort the empid and select the top row after sorting,
i can sort the table using "select * from emp order by empid desc,
i can select the top row using "select * from emp where rownum=1"
i want a combination of the 2,
pls provide me the required query
Thanks and Regards,
Saurabh JhunjhunwalaSEELCT *
FROM ( SELECT e.*
, ROWNUM row_num
FROM emp e
ORDER BY empid desc
WHERE row_num = 1Regards
Arun -
Select top row in Single Query?
Hi
Can somebody help me to write a query to get the first row after order by clause using single query alone.
Example:
I can write following query to select first row
select * from (selec * from t order by col1) where rownum = 1;
But here I should not use inline view to get the result. Because my original requirement needs to use this query in select list and it needs to use a column (of a table from the FROM clause) in the where clause of inline query. Because there is restriction that we can not use the column (of a table from the FROM clause) more than one level of inline query.
Please help me.Raghav.786 wrote:
Hi
Can somebody help me to write a query to get the first row after order by clause using single query alone.
Example:
I can write following query to select first row
select * from (selec * from t order by col1) where rownum = 1;
But here I should not use inline view to get the result. Because my original requirement needs to use this query in select list and it needs to use a column (of a table from the FROM clause) in the where clause of inline query. Because there is restriction that we can not use the column (of a table from the FROM clause) more than one level of inline query.
Please help me.
What Oracle version are you?
If you have 12c you can use
select col1,...
from t
order by col1
fetch first 1 row only;
If less than 12c, you have can't do it without a subquery.
What are you actually trying to do? Read Re: 2. How do I ask a question on the forums?
and follow the advice there by giving example create table and insert sample data statements and
explaining clearly what you are trying to do. Then we can help more. -
hi,
pls I have this issue that needs to be resolved. I need to select top five rows from a table depending on the values of a column stock_value. pls I will appreciate if someone can help me out, Francois pls try and help
This is the senerio:
I have a table stock, on the table I have company_name, stock_value, sector.
Now I want to get top five rows from this table depending on the five highest value of stock_value and for each sector.
lets try and write a query that will retrive the records after that I will put it in a procedure.
I know am suppose to ask this on mssql forum but most mssql forums takes time to reply and this is very urgent cos I have to deliver in 45 minutes time
thank you very much
jideoforhy,
try out:
select s.name, sp. sp_sales total_sales
from salesperson s,
(select salesperson_id,sum(tot_sales) sp_sales
RANK() OVER (ORDER BY SUM(tot_SALES) desc) SALES_RANK
FROM ORDERS
WHERE YEAR = 2006
group by salesperson_id) sp
where sp.sales_rank <= 5 (...n)
and sp.salesperson_id = s.salesperson_id
order by sq.sales_rank;
give result in:
name total_sales
a 100
b 90
c 80
d 70
e 60
hope help you
regards -
How can i select some row from multiple row in the same group of data
I want to select some row from multiple row in the same group of data.
ColumnA
Column B
1 OK
1 NG
2 NG
2 NG
3 OK
3 OK
I want the row of group of
ColumnA if ColumnB contain even 'NG'
row , select only one row which Column B = 'NG'
the result i want =
ColumnA Column B
1 NG
2 NG
3 OK
Thank youThat's some awful explanation, but I think this is what you were driving at:
DECLARE @forumTable TABLE (a INT, b CHAR(2))
INSERT INTO @forumTable (a, b)
VALUES
(1, 'OK'),(1, 'NG'),
(2, 'NG'),(2, 'NG'),
(3, 'OK'),(3, 'OK')
SELECT f.a, MIN(COALESCE(f2.b,f.b)) AS b
FROM @forumTable f
LEFT OUTER JOIN @forumTable f2
ON f.a = f2.a
AND f.b <> f2.b
GROUP BY f.a -
Selecting top 10 rows based on one column.
Hi,
I need to display the top 10 records for each distinct value of a column.USE Northwind;
-- Solution 1
SELECT S.SupplierID, S.CompanyName, CA.ProductID, CA.UnitPrice
FROM dbo.Suppliers AS S
CROSS APPLY
(SELECT TOP (10) *
FROM dbo.Products AS P
WHERE P.SupplierID = S.SupplierID
ORDER BY UnitPrice DESC, ProductID DESC) AS CA
ORDER BY S.SupplierID, CA.UnitPrice DESC, CA.ProductID DESC;
-- Solution 2
WITH C AS
SELECT S.SupplierID, S.CompanyName, P.ProductID, P.UnitPrice,
ROW_NUMBER() OVER(
PARTITION BY P.SupplierID
ORDER BY P.UnitPrice DESC, P.ProductID DESC) AS RowNum
FROM dbo.Suppliers AS S
JOIN dbo.Products AS P
ON P.SupplierID = S.SupplierID
SELECT SupplierID, CompanyName, ProductID, UnitPrice
FROM C
WHERE RowNum <= 10
ORDER BY SupplierID, ProductID DESC, UnitPrice DESC;
Best Regards,Uri Dimant SQL Server MVP,
http://sqlblog.com/blogs/uri_dimant/
MS SQL optimization: MS SQL Development and Optimization
MS SQL Consulting:
Large scale of database and data cleansing
Remote DBA Services:
Improves MS SQL Database Performance
SQL Server Integration Services:
Business Intelligence -
How to select top one in CDS view ?
I have tried following logic to select top one in CDS view but its giving error -
define view Cds_View_First_Reference as select top one CReferredObject from CDSVIEWCROSSREFHi Ruchi,
since you posted this question in "ABAP in Eclipse" I assume you are asking about CDS in ABAP. This is important because the CDS features sets in ABAP and (native) HANA are different.
Be that as it may,, SELECT TOP 1 is neither supported in the CDS implementation in ABAP nor in HANA.
In ABAP you might consider using the min() or max() function together with the appropriate GROUP BY clause in the CDS view (depending on what you want to achieve), but you can also easily "implement" this in the Open SQL statement which selects from your CDS view.
Using the additions SELECT SINGLE or UP TO 1 ROWS and an appropriate ORDER BY clause in Open SQL, you can achieve the same as SELECT TOP 1.
Unfortunately there is currently no possibility to define a view which delivers the TOP 1 which you can again use in another view ("view on view").
Kind regards
Chris -
Convert "select top 5 ..." in Oracle8i
-- We are in the process of migrating application from SQLserver7 to Oracle8i,
-- and trying to convert a procedure to return top 5
-- rows given a search string.
-- In SQLserver7, "select top 5 ... "
-- The Oracle8i Application Developer's Guide - Fundamentals
-- recommends to use rownum, the query runs OK in SQL*Plus,
-- but gets error when used in a procedure with returned cursor.
-- Is there any solution for it?
-- Following is the sample query and procedure (in a package)
-- Query returns top 5 rows
select t.rank, t.productid, t.productname
from (
Select score(0) as rank, productid, productname
from Product
where status = 'A'
and contains(productname, 'Frog', 0) > 0
order by rank desc, productid
) t
where rownum < 6;
-- Proc Name: Pr_Test
-- Purpose: Retrieve product data for a specified search string
CREATE OR REPLACE PACKAGE pkg_test
IS
TYPE RT1 IS RECORD (
Rank NUMBER(10),
ProductID Product.ProductID%TYPE,
ProductName Product.ProductName%TYPE
TYPE RCT1 IS REF CURSOR RETURN RT1;
PROCEDURE pr_test
(i_searchstring IN VARCHAR2 ,
io_prdcursor IN OUT RCT1);
END pkg_test;
CREATE OR REPLACE PACKAGE BODY pkg_test
AS
PROCEDURE pr_test
(i_searchstring IN VARCHAR2 ,
io_prdcursor IN OUT RCT1)
IS
BEGIN
OPEN io_prdcursor FOR
select t.rank, t.productid, t.productname
from (
Select score(0) as rank, productid, productname
from Product
where status = 'A'
and contains(productname, i_searchstring, 0) > 0
order by rank desc, productid
) t
where rownum < 6;
END pr_test;
END pkg_test;
-- Following is the error message when compiling the package body:
Warning: Package Body created with compilation errors.
SQL> show error
Errors for PACKAGE BODY PKG_TEST:
LINE/COL ERROR
19/7 PLS-00103: Encountered the symbol "ORDER" when expecting one of
the following:
) * & - + / mod rem with an exponent (**) and or group having
intersect minus start union where connect | |
The symbol ")" was substituted for "ORDER" to continue.
20/11 PLS-00103: Encountered the symbol ")" when expecting one of the
following:
. ( , * @ % & - + ; / for mod rem an exponent (**) asc desc
| |
-- Run the procedure and get the results
declare
i number := 0;
v_string varchar2(50) := 'CAT';
-- v_string varchar2(50) := 'FROG%';
v_RC1 pkg_test.RCT1;
v_Score NUMBER(10);
v_ProductID Product.ProductID%TYPE;
v_ProductName Product.ProductName%TYPE;
begin
pkg_test.pr_test (v_string, v_RC1);
LOOP
FETCH v_RC1 INTO v_Score,v_ProductID,v_ProductName;
EXIT WHEN (v_RC1%NOTFOUND);
DBMS_OUTPUT.put_line(substr('Score='| |v_score| |', ProdID='| |v_ProductID ,1,255));
i := i + 1;
END LOOP;
DBMS_OUTPUT.put_line('Total '| |i| |' records retrieved.');
end;
nullhttp://www.orafaq.org/faqsql.htm#TOP
This may be of use, the plsql cursor declaration syntax may not have all the facilities of runnning the query from sqlplus:
How does one select the TOP N rows from a table?
Form Oracle8i one can have an inner-query with an ORDER BY clause. Look at this example:
SELECT *
FROM (SELECT * FROM my_table ORDER BY col_name_1 DESC)
WHERE ROWNUM < 10;
Use this workaround with prior releases:
SELECT *
FROM my_table a
WHERE 10 >= (SELECT COUNT(DISTINCT maxcol)
FROM my_table b
WHERE b.maxcol >= a.maxcol)
ORDER BY maxcol DESC;
Turloch -
How do I select a row from the middle of a recordset?
UserID QuestionID Answered
10 9 N
10 8 N
10 7 N
10 6 N
10 5 Y
10 4 Y
10 1 Y
From the table sorted by QuestionID DESC, how do I select the first row from the bottom going up with Answered value equal to 'N'?
Which in the example above would be:
10 6 N
I need to select this row and get the QuestionID value equal to 6.
Right now I have:
select QuestionID
from tblMap
where Answered = 'N'
and ROWNUM = 1
order by QuestionID ASC;
This always the top most row, which would be:
10 9 NHere i used DUAL to generate a list of numbers for me.
ME_XE?select *
2 from
3 (
4 select row_number() over (order by col1 desc) as rn, count(*) over() as cnt, col1
5 from
6 (
7 select level as col1 from dual connect by level <= 9
8 )
9 )
10 where ceil(cnt/2) = rn
11 /
RN CNT COL1
5 9 5
1 row selected.
Elapsed: 00:00:00.07
ME_XE?Edited by: Tubby on Jul 8, 2009 1:47 PM
Seems i misread the question :) -
Can't select certain rows in datagrid
Hello,
I have a datagrid with 3 columns, that works great until you have 2 rows next to each other w/ the exact first name and last name.
When that happens, I can select the top row but I can't select the bottom row.
If I trace the onPatientSelected method, it never gets called.
here's my datagrid code below:
<code>
<mx:DataGrid
id="patientList"
dataProvider="{dataProvider}"
change="onPatientSelected()"
styleName="patientlist"
width="100%"
height="100%"
editable="false"
draggableColumns="false"
resizableColumns="false" headerRelease="checkColumnSorted(event)">
<mx:columns>
<mx:DataGridColumn headerText="Last Name" dataField="LastName" />
<mx:DataGridColumn headerText="First Name" dataField="FirstName"/>
<mx:DataGridColumn headerText="Unique Id" dataField="UniqueId" sortable="false"/>
</mx:columns>
</mx:DataGrid>
</cod>
Any ideas?The strange thing is that we have datadrids all over this app that are formatted exactly the same way and this behavior never happens:
Here's another example:
<code>
<mx:DataGrid
id="contactDataGrid"
change="onItemSelected()"
styleName="patientlist"
width="50%"
height="100%"
editable="false"
draggableColumns="false"
resizableColumns="false" >
<mx:columns>
<mx:DataGridColumn headerText="Name" dataField="FirstName" />
<mx:DataGridColumn headerText="Relationship" dataField="RelationshipToPatientTypeId"/>
</mx:columns>
</mx:DataGrid>
</code> -
How do I get the numbers program to type a numerical date across the top row? It wants to change it to Dec. 13 instead of 12/13.
Amy,
I hope that you can forgive Numbers for converting the date you enter as 12/13 into the default format of "December 13, 2011", one that is popular with many users.
You can change to any of the supported date formats by using the Cells Inspector, Date and Time options.
Select the top row of cells and use the inspector to set the format. You may do this before or after making the entries.
Jerry -
i have this query to count people who are in different deployment
SELECT Trade.Trade, Trade.Auth,
(select count(tradeno) from Member where trade=Trade.Trade) AS Held,
(select count(tradeno) from Member where trade=Trade.Trade and Status='Present') AS Present,
(select count(tradeno) from Member where trade=Trade.Trade and Status='KL') AS KL,
(select count(tradeno) from Member where trade=Trade.Trade and Status='HL') AS HL,
(select count(tradeno) from Member where trade=Trade.Trade and Status='SL') AS SL,
(select count(tradeno) from Member where trade=Trade.Trade and Status='TTT') AS TTT,
(select count(tradeno) from Member where trade=Trade.Trade and Status='COURSE') AS COURSE,
(select count(tradeno) from Member where trade=Trade.Trade and Status='UD') AS UD,
(select count(tradeno) from Member where trade=Trade.Trade and Status='LAW') AS LAW,
(select count(tradeno) from Member where trade=Trade.Trade and Status='MAL') AS MAL
FROM Trade ORDER BY id"
the above query works for me fine. now there is a table named PL with field PL
PL
KM
KT
KM
HG
TG
HG
i want to make six different queries for each PL. add a clause in above query
1. to select top 1 PL and also add where clause in the above query so that people employed in KM only gets counted and displayed
2. to select second row of PL and also add where clause in the above query so that people employed in KT only
gets counted and displayed
as also for all other PL. please lelp me
I am a System Administrator at VadodaraSir
The first query which i had given is correct and it works for me. Now i want to add one more
clause that PL.PL and that PL should be dynamically selected and not manually added in query. The logic should be like this
Above query + where PL.PL= second row of table PL that is the result required for me
First problem is : I was not able to add the clause WHERE PL.PL=' '
Second Problem is : If i had solved my first one the PL.PL must be automatically selected as
i had given a sample query to select the second row from table PL.
Then it is solved
I am a System Administrator at Vadodara -
So when i look up something like "shoes" in the amazon search box the top row of items moves over to the far right. And most are no longer even on my screen
I checked on I.E. and i had no issues with this so i assume its a firefox issue.'''Try the Firefox Safe Mode''' to see how it works there. The Safe Mode is a troubleshooting mode, which disables most add-ons.''
''(If you're not using it, switch to the Default theme.)''
* You can open the Firefox 4.0+ Safe Mode by holding the '''Shift''' key when you use the Firefox desktop or Start menu shortcut.
* Or use the Help menu item and click on the '''Restart with Add-ons Disabled...''' menu item while Firefox is running.
''Don't select anything right now, just use "'Start in Safe Mode"''
''To exit the Firefox Safe Mode, just close Firefox and wait a few seconds before using the Firefox shortcut (without the Shift key) to open it again.''
'''''If it is good in the Firefox Safe Mode''''', your problem is probably caused by an extension, and you need to figure out which one.
Please follow the [[Troubleshooting extensions and themes]] article for that.
''When you figure out what's causing your issues, please let us know. It might help other users who have the same problem.'' -
Selecting a row in the output of alv grid
hi,
how do i select a row in the output of alv grid?plz help...
regards,
sheeba.Hi,
Please refer the code below:
*& Report ZDEMO_ALVGRID_SELROW *
*& Example of a simple ALV Grid Report *
*& The basic ALV grid, Enhanced to display capture each row a user has *
*& selected *
REPORT zdemo_alvgrid_selrow .
TABLES: ekko.
type-pools: slis. "ALV Declarations
*Data Declaration
TYPES: BEGIN OF t_ekko,
SEl, "stores which row user has selected
ebeln TYPE ekpo-ebeln,
ebelp TYPE ekpo-ebelp,
statu TYPE ekpo-statu,
aedat TYPE ekpo-aedat,
matnr TYPE ekpo-matnr,
menge TYPE ekpo-menge,
meins TYPE ekpo-meins,
netpr TYPE ekpo-netpr,
peinh TYPE ekpo-peinh,
END OF t_ekko.
DATA: it_ekko TYPE STANDARD TABLE OF t_ekko INITIAL SIZE 0,
wa_ekko TYPE t_ekko.
*ALV data declarations
data: fieldcatalog type slis_t_fieldcat_alv with header line,
gd_tab_group type slis_t_sp_group_alv,
gd_layout type slis_layout_alv,
gd_repid like sy-repid.
*Start-of-selection.
START-OF-SELECTION.
perform data_retrieval.
perform build_fieldcatalog.
perform build_layout.
perform display_alv_report.
*& Form BUILD_FIELDCATALOG
* Build Fieldcatalog for ALV Report
form build_fieldcatalog.
* There are a number of ways to create a fieldcat.
* For the purpose of this example i will build the fieldcatalog manualy
* by populating the internal table fields individually and then
* appending the rows. This method can be the most time consuming but can
* also allow you more control of the final product.
* Beware though, you need to ensure that all fields required are
* populated. When using some of functionality available via ALV, such as
* total. You may need to provide more information than if you were
* simply displaying the result
* I.e. Field type may be required in-order for
* the 'TOTAL' function to work.
fieldcatalog-fieldname = 'EBELN'.
fieldcatalog-seltext_m = 'Purchase Order'.
fieldcatalog-col_pos = 0.
fieldcatalog-outputlen = 10.
fieldcatalog-emphasize = 'X'.
fieldcatalog-key = 'X'.
* fieldcatalog-do_sum = 'X'.
* fieldcatalog-no_zero = 'X'.
append fieldcatalog to fieldcatalog.
clear fieldcatalog.
fieldcatalog-fieldname = 'EBELP'.
fieldcatalog-seltext_m = 'PO Item'.
fieldcatalog-col_pos = 1.
append fieldcatalog to fieldcatalog.
clear fieldcatalog.
fieldcatalog-fieldname = 'STATU'.
fieldcatalog-seltext_m = 'Status'.
fieldcatalog-col_pos = 2.
append fieldcatalog to fieldcatalog.
clear fieldcatalog.
fieldcatalog-fieldname = 'AEDAT'.
fieldcatalog-seltext_m = 'Item change date'.
fieldcatalog-col_pos = 3.
append fieldcatalog to fieldcatalog.
clear fieldcatalog.
fieldcatalog-fieldname = 'MATNR'.
fieldcatalog-seltext_m = 'Material Number'.
fieldcatalog-col_pos = 4.
append fieldcatalog to fieldcatalog.
clear fieldcatalog.
fieldcatalog-fieldname = 'MENGE'.
fieldcatalog-seltext_m = 'PO quantity'.
fieldcatalog-col_pos = 5.
append fieldcatalog to fieldcatalog.
clear fieldcatalog.
fieldcatalog-fieldname = 'MEINS'.
fieldcatalog-seltext_m = 'Order Unit'.
fieldcatalog-col_pos = 6.
append fieldcatalog to fieldcatalog.
clear fieldcatalog.
fieldcatalog-fieldname = 'NETPR'.
fieldcatalog-seltext_m = 'Net Price'.
fieldcatalog-col_pos = 7.
fieldcatalog-outputlen = 15.
fieldcatalog-do_sum = 'X'. "Display column total
fieldcatalog-datatype = 'CURR'.
append fieldcatalog to fieldcatalog.
clear fieldcatalog.
fieldcatalog-fieldname = 'PEINH'.
fieldcatalog-seltext_m = 'Price Unit'.
fieldcatalog-col_pos = 8.
append fieldcatalog to fieldcatalog.
clear fieldcatalog.
endform. " BUILD_FIELDCATALOG
*& Form BUILD_LAYOUT
* Build layout for ALV grid report
form build_layout.
gd_layout-box_fieldname = 'SEL'.
"set field name to store row selection
gd_layout-edit = 'X'. "makes whole ALV table editable
gd_layout-zebra = 'X'.
endform. " BUILD_LAYOUT
*& Form DISPLAY_ALV_REPORT
* Display report using ALV grid
form display_alv_report.
gd_repid = sy-repid.
call function 'REUSE_ALV_GRID_DISPLAY'
exporting
i_callback_program = gd_repid
* i_callback_top_of_page = 'TOP-OF-PAGE' "see FORM
i_callback_user_command = 'USER_COMMAND'
* i_grid_title = outtext
is_layout = gd_layout
it_fieldcat = fieldcatalog[]
* it_special_groups = gd_tabgroup
* IT_EVENTS = GT_XEVENTS
i_save = 'X'
* is_variant = z_template
tables
t_outtab = it_ekko
exceptions
program_error = 1
others = 2.
if sy-subrc <> 0.
* MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
* WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
endif.
endform. " DISPLAY_ALV_REPORT
*& Form DATA_RETRIEVAL
* Retrieve data form EKPO table and populate itab it_ekko
form data_retrieval.
select ebeln ebelp statu aedat matnr menge meins netpr peinh
up to 10 rows
from ekpo
into corresponding fields of table it_ekko.
endform. " DATA_RETRIEVAL
* FORM USER_COMMAND *
* --> R_UCOMM *
* --> RS_SELFIELD *
FORM user_command USING r_ucomm LIKE sy-ucomm
rs_selfield TYPE slis_selfield.
* Check function code
CASE r_ucomm.
WHEN '&IC1'.
* Check field clicked on within ALVgrid report
IF rs_selfield-fieldname = 'EBELN'.
* Read data table, using index of row user clicked on
READ TABLE it_ekko INTO wa_ekko INDEX rs_selfield-tabindex.
* Set parameter ID for transaction screen field
SET PARAMETER ID 'BES' FIELD wa_ekko-ebeln.
* Sxecute transaction ME23N, and skip initial data entry screen
CALL TRANSACTION 'ME23N' AND SKIP FIRST SCREEN.
ENDIF.
WHEN '&DATA_SAVE'. "user presses SAVE
loop at it_ekko into wa_ekko.
if wa_ekko-sel EQ 'X'.
* Process records that have been selected
endif.
endloop.
ENDCASE.
ENDFORM.
Thanks,
Sriram Ponna. -
How to select a row from duplicate set of records?
I want to select a row from a duplicate set of records.
below is the explanation of my requirement.
select * from test_dup;
COL_BILL COL_SERV COL_SYS
b1 s1 c
b1 s1 g
b1 s2 c
b1 s2 g
b2 s2 g
b2 s3 c
b2 s3 g
b3 s3 c
Here what I want is, for a distinct col_sys if col_bill and col_serv is same then I need the row where col_sys='c'
from the above result set I need the following:
b1 s1 c
b1 s2 c
b2 s3 c
I am using the following SQL query which is giving me the correct result set. But it will hamper the performance because there are total 45 columns in the table and total volume is around 50 million.
select * from test_dup where col_bill||col_serv in (
select col_bill||col_serv from (
select col_bill,col_serv,count(*) from test_dup
where col_sys in ('c','g')
group by col_bill,col_serv having count(*) >1)) and
col_sys='c';
Can anyone please provide me the optimize SQL query for the same.Hi,
Another way,
SQL> with test_dup
as
select 'b1' col_bill, 's1' col_serv, 'c' col_sys from dual union all
select 'b1', 's1', 'g' from dual union all
select 'b1', 's2', 'c' from dual union all
select 'b1', 's2', 'g' from dual union all
select 'b2', 's2', 'g' from dual union all
select 'b2', 's3', 'c' from dual union all
select 'b2', 's3', 'g' from dual union all
select 'b3', 's3', 'c' from dual
select col_bill, col_serv, min(col_sys) col_sys
from test_dup
where col_sys in ('c', 'g')
group by col_bill, col_serv
having count( * ) > 1
and count(nullif(col_sys, 'g')) > 0;
CO CO C
b1 s1 c
b2 s3 c
b1 s2 c
3 rows selected.Regards
Peter
Edited by: Peter on Feb 18, 2009 1:10 AM
- Added test data, thanks Karthick
Maybe you are looking for
-
How to use default values of variables when data get varied
Hi Expert, I want to use default value of variables var1. for eg. if variable length is 20 char and value is abc , then i want to fill var1 by default 20 ( after printing abc value remaining length i.e.17 should be taken by var1 means total length 20
-
Hi SDNites, My requirement is to upload document in SAP DMS and this document we are receiving from an external system. Can you please let me know, 1. Is there any way I can provide a link in ECC SAP DMS for the documents which are stored in external
-
Window.close doesn't work with Firefox
I have used the code from the followinging reference on OTN to close my window: Closing brower window It works fine for IE, but not for Firefox. How can I make it work with Firefox?
-
Tips for ensuring iOS compatibility?
Are there any tips for ensuring that iWork Pages on the Mac is limited to the functionality and fonts supported by the iOS Pages app?
-
Itunes won't sync yosemite (external drive)
I have an external drive and with the new update (of yosemite and the new itunes) my music library won't sync. It is on an external drive. I have tried the previous method (preferences, advanced, itunes media folder location--change)... but it does