Help in Select query please

Hi, How I can split the column (Root_Desc) into five. Need to split column after the hyphen ('_').
Select * from travel
Root_Desc
1100_AUS_04_RTOT_GT
1102_USA_3_RTOT_TT
Desired Output
Rout_No Dest_Country Desc_Code Rout_Desc Rout_Line
1100     AUS   04    RTOT    GT
1102     USA    3     RTOT   TT
Thanks.

You can use split function, say,
declare @travel table (Root_Desc varchar(max));
insert into @travel (Root_Desc) values ('1100_AUS_04_RTOT_GT'),('1102_USA_3_RTOT_TT');
;with cte as (select t.Root_Desc, F.Value, F.Id from @travel t
CROSS APPLY dbo.fnSplit(t.Root_Desc, '_') F)
select Root_Desc, [1] as Rout_No, [2] as Dest_Country,
[3] as Desc_Code,
[4] as Rout_Desc,
[5] as Rout_Line
from cte PIVOT (min(value) for ID IN ([1],[2],[3],[4],[5])) pvt
where fnSplit is table-valued function:
USE [AllTests]
GO
/****** Object: UserDefinedFunction [dbo].[fnSplit] Script Date: 1/5/2015 11:47:32 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Test query
CREATE FUNCTION [dbo].[fnSplit]
(@list VARCHAR(8000),
@delim CHAR(1) = ','
) RETURNS TABLE AS
RETURN
WITH csvtbl(START, stop) AS (
SELECT START = 1,
stop = CHARINDEX(@delim COLLATE Slovenian_BIN2, @list + @delim)
UNION ALL
SELECT START = stop + 1,
stop = CHARINDEX(@delim COLLATE Slovenian_BIN2,
@list + @delim, stop + 1)
FROM csvtbl
WHERE stop > 0
SELECT row_number() over (order by Start) as ID, LTRIM(RTRIM(SUBSTRING(@list, START,
CASE WHEN stop > 0 THEN stop - START ELSE 0 END)))
AS VALUE
FROM csvtbl
WHERE stop > 0
GO
For every expert, there is an equal and opposite expert. - Becker's Law
My blog
My TechNet articles

Similar Messages

  • I need to know the proper syntax for my SELECT query, please.

    Hello All,
    Quick one for you:
    Let's say that I have several columns in a table with names such as subject_1, subject_2, subject_3, etc. The table's name is subject_names.
    The number in each of the three column name examples is also a value passed along a query string, the user can select choices, 1, 2 or 3. That query string's variable is $qs.
    So, what I want is a SELECT query that uses the query string value as follows (KEEP IN MIND, I know this is not the proper syntax):
    "SELECT subject_[$qs]
    FROM subject_names";
    I have tried all sorts of cominations of quotes (single and double), dots, brackets, braces and parenthesis. I just want to know how to include such a variable within this code.
    Any and all help is sincerely appreciated!
    Cheers,
    wordman

    Well, I did give you the syntax though.
    $query = 'SELECT ' . $qs . ' FROM tbl_name';
    I put spaces between the periods this time to make it more clear.
    If you put the actual word 'subject' in there and just want your form to name it's options as the numbers available you could do this:
    $query = 'SELECT subject_' . $qs . ' FROM tbl_name';
    In PHP you can use either single or double quotes around your query string, I always just use single quotes. I see a lot of other use double quotes.
    Double quotes would look like:
    $query = "SELECT subject_' . $qs . ' FROM tbl_name";
    Or when using double quotes you can actually just place the variable right in the string without having to concatenate multiple strings like above.
    Since you mentioned that you are good with passing variables I probably don't have to mention that you need to set the value attribute of your option tags (if you are using a select) to the value you want them to pass.
    Ex:
    <select name="choices">
         <option value="1">1</option>
         <option value="2">2</option>
         <option value="3">3</option>
    </select>
    If you have that part all figured out then you can use the syntax above for your query string.
    Good luck.

  • Plz help, A select query for table giving foll o/p

    A table has a single column with following data
    Col1
    170
    10
    140
    520
    20
    60
    70
    The select query should return the data in the following format
    Col1 Col2 Col3 Col4
    170 3 1 0
    10 0 0 1
    140 2 2 0
    520 10 1 0
    20 0 1 0
    60 1 0 1
    70 1 1 0

    Using my awesome puzzle solving brain I note that Col2 = 50 Col3 = 20 Col4 = 10.
    But you should be telling US that.
    select col1, floor(col1/50) col2, floor(mod(col1,50)/20) col3, floor(mod(mod(col1,50),20)/10) col4
    from mytable.
    I win the internets!
    Edited by: Dave Hemming on Dec 19, 2008 11:35 AM

  • Need help in Select Query

    Hello,
    I am using oracle 9i and windows XP:
    Please help me to making a query to get output as mentioned below:
    create table myt(col1 varchar2(10));
    insert into myt values('TABLE1');
    insert into myt values('TABLE2');
    insert into myt values('TABLE3');
    COMMIT;
    create table table1(name varchar2(10),amount number);
    create table table2(name varchar2(10),amount number);
    create table table3(name varchar2(10),amount number);
    insert into table1 values('James',1000);
    insert into table1 values('David',1500);
    insert into table1 values('James',2000);
    insert into table1 values('David',1735);
    insert into table2 values('Menon',500);
    insert into table2 values('Martin',700);
    COMMIT;
    Required Output:
    Table Name
    Table1
        James: 3000
        David: 3235
        Sum:   6235
    Table2
        Menon:  500
        Martin: 700
        Sum:   1200
             -------Regards

    In your solution i added some modifications and got the output:
    declare
    cr_lf varchar2(2) := chr(13) || chr(10);
    the_cursor sys_refcursor;
    the_sql varchar2(4000) := 'select * from ' || cr_lf || '(' || cr_lf;
    a_table varchar2(10);
    ln varchar2(10);
    a_name varchar2(10);
    an_amount number:=0;
    tan_amt number:=0;
    i number;
    j varchar2(4000);
    begin
    for the_row in (select col1 from myt) loop
    the_sql := the_sql || 'select ''' || the_row.col1 || ''',name,sum(amount) from ' || the_row.col1 || ' group by name ' || cr_lf;
    the_sql := the_sql || 'union all' || cr_lf;
    end loop;
    the_sql := substr(the_sql,1,length(the_sql) - 11) || ')' || cr_lf;
    i := 1;
    j := instr(the_sql,cr_lf,i);
    while i > 0 loop
    exit when j = 0;
    dbms_output.put_line(substr(the_sql,i,j - i));
    i := j + 2;
    j := instr(the_sql,cr_lf,i);
    end loop;
    dbms_output.put_line(substr(the_sql,i));
    --dbms_output.put_line(the_sql);
    open the_cursor for the_sql;
    dbms_output.put_line('--------------------------------------------------------------------------');
    dbms_output.put_line(rpad('TABLE',20) || ' ' || rpad('NAME',20) || ' ' || rpad('AMOUNT',20));
    dbms_output.put_line('--------------------------------------------------------------------------');
    loop
    ln:= a_table;
    fetch the_cursor into a_table,a_name,an_amount;
    exit when the_cursor%notfound;
    if ln<>a_table then
    dbms_output.put_line('--------------------------------------------------------------------------');
    dbms_output.put_line(rpad('SUM',40) || lpad(to_char(tan_amt),10));
    dbms_output.put_line('--------------------------------------------------------------------------');
    tan_amt:=0;
    end if;
    tan_amt:= tan_amt+an_amount;
    dbms_output.put_line(rpad(a_table,20) || ' ' || rpad(a_name,20) || ' ' || rpad(an_amount,20));
    end loop;
    dbms_output.put_line('--------------------------------------------------------------------------');
    --dbms_output.put_line(rpad('SUM',45) || to_char(tan_amt));
    dbms_output.put_line(rpad('SUM',40) || lpad(to_char(tan_amt),10));
    dbms_output.put_line('--------------------------------------------------------------------------');
    close the_cursor;
    end;
    select * from
    select 'TABLE1',name,sum(amount) from TABLE1 group by name
    union all
    select 'TABLE2',name,sum(amount) from TABLE2 group by name
    union all
    select 'TABLE3',name,sum(amount) from TABLE3 group by name
    TABLE                  NAME                  AMOUNT
    TABLE1                 David                  6470
    TABLE1                 James                  6000
    SUM                                          12470
    TABLE2                 Martin                 1400
    TABLE2                 Menon                  1000
    SUM                                           2400
    --------------------------------------------------------------------------So many thanks for providing solution to me.
    Regards

  • Help In Select Query

    Dear All,
    I have oracle 10G R2 On windows.
    below is my query :-
    select a.foliono,a.schcode,sum(a.amount)-sum(b.amount)as Difference_Amount from
    processed_tran_split a, systematic_purchase b
    where a.folio=b.folio and a.schcode=b.schcode and a.trxntypcod='P' and a.trxsubtypc='S' and
    Difference_Amount >0
    group by a.foliono,a.schcode
    when i execute above query it say's "Difference_Amount" invalid identifier.
    My need is foliono,schcode and processed_tran_split amount minus(-) systematic_purchase amount and Resulting Amount should be >0.
    Please help.
    Saludos.
    CHanchal Wankhade.

    select a.foliono,a.schcode,sum(a.amount)-sum(b.amount)as Difference_Amount from
    processed_tran_split a, systematic_purchase b
    where a.folio=b.folio and a.schcode=b.schcode and a.trxntypcod='P' and a.trxsubtypc='S' and
    Difference_Amount >0
    group by a.foliono,a.schcode
    when i execute above query it say's "Difference_Amount" invalid identifier.
    My need is foliono,schcode and processed_tran_split amount minus(-) systematic_purchase amount and Resulting Amount should be >0.You cant use the column alias in the predicate.
    Just use
    sum(a.amount)-sum(b.amount) >0regards

  • SQL I need help with this query Please help

    List the names of all the products whose weight unit measure is “Gram”.  Order the list by product name.  Do not use JOINS, but use the IN clause with a sub-query.
    select Name
    from UnitMeasure
    where Name= 'Gram'
    order by Name
    I did this, but it seem that the requirement is different.

    As a guess:
    Select Name from Product
    where UnitMeasure in (Select Name from unitmeasure where name = 'Gram')
    Andy Tauber
    Data Architect
    The Vancouver Clinic
    Website | LinkedIn
    This posting is provided "AS IS" with no warranties, and confers no rights. Please remember to click
    "Mark as Answer" and "Vote as Helpful" on posts that help you. This can be beneficial to other community members reading the thread.

  • Can any one help with this query please

    I have a table something as below
    Things_t
    Things Characteristic Char Value
    Item 1 Colour Red
    Item 1 Packaging
    Item 2 Shape Square
    Item 2 Brand Spunk
    Now i want to reterive an item with none of its char values as Null. Using the query “ select distinct things from things_t where char value is Null ” will fetch the item 1 also together with item 2. i want to fetch a record from thing for which none of the char values are Null such as Item 2. Can you please help me with this query.

    Try this:
    WITH t AS
    (SELECT 1 item_id, 17436 chr_id, 14225034 chr_val_id FROM dual UNION
    SELECT 1 item_id, 39 chr_id, 14276173 chr_val_id FROM dual UNION
    SELECT 1 item_id, 17774 chr_id, NULL chr_val_id FROM dual UNION
    SELECT 1 item_id, 265 chr_id, 20502978 chr_val_id FROM dual UNION
    SELECT 1 item_id, 16978 chr_id, 797233 chr_val_id FROM dual UNION
    SELECT 1 item_id, 13092 chr_id, 5666917 chr_val_id FROM dual UNION
    SELECT 1 item_id, 15228 chr_id, 1209758 chr_val_id FROM dual UNION
    SELECT 2 item_id, 112 chr_id,  12705342 chr_val_id FROM dual UNION
    SELECT 2 item_id, 6945 chr_id, NULL chr_val_id FROM dual UNION
    SELECT 2 item_id, 70 chr_id, 12597376 chr_val_id FROM dual UNION
    SELECT 2 item_id, 16832 chr_id, NULL chr_val_id FROM dual UNION
    SELECT 2 item_id, 7886 chr_id, 9588619 chr_val_id FROM dual UNION
    SELECT 2 item_id, 6986 chr_id, 2659351 chr_val_id FROM dual UNION
    SELECT 3 item_id, 9531 chr_id, 8910943 chr_val_id FROM dual UNION
    SELECT 3 item_id, 9798 chr_id, 8717531 chr_val_id FROM dual UNION
    SELECT 3 item_id, 17446 chr_id, 12266441 chr_val_id FROM dual UNION
    SELECT 3 item_id, 4830 chr_id, 13683090 chr_val_id FROM dual UNION
    SELECT 3 item_id, 9518 chr_id, 834772 chr_val_id FROM dual UNION
    SELECT 3 item_id, 11031 chr_id, 20233753 chr_val_id FROM dual UNION
    SELECT 3 item_id, 12564 chr_id, 2282478 chr_val_id FROM dual)
    SELECT DISTINCT item_id
    FROM   t
    MINUS
    SELECT DISTINCT item_id
    FROM   t
    WHERE  chr_val_id IS NULLOr this:
    SELECT item_id
    FROM  (SELECT   item_id,
                    MIN(NVL(chr_val_id, -1)) min_chr_val_id
           FROM     t
           GROUP BY item_id)
    WHERE  min_chr_val_id != -1Edited by: lee200 on Oct 15, 2012 9:22 AM

  • Need help on select query

    Hi,
    I have a query which will produce me the below data:
    DataTime SLA Met Time
    20101212 12/13/2010 12:48:29 PM
    20101211 12/12/2010 4:50:38 PM
    20101210 12/11/2010 2:07:02 PM
    20101209 12/11/2010 9:46:30 AM
    20101208 12/10/2010 4:46:19 AM
    Now with the above data I want to find "sla status". Below is the condition:
    1. if datatime is 20101212 (yyyymmdd) and if sla is met on or before 20101212 6pm then it has to print sla status as "MET", by any chance if sla is met after 6pm then it has to print as "Not Met".
    2. So we dont have any static data in table and we have around 20k rows in the table.
    3. Datatime is a Number column.
    Please help me on this. Thanks

    user497267 wrote:
    Hi,
    I have a query which will produce me the below data:
    DataTime SLA Met Time
    20101212 12/13/2010 12:48:29 PM
    20101211 12/12/2010 4:50:38 PM
    20101210 12/11/2010 2:07:02 PM
    20101209 12/11/2010 9:46:30 AM
    20101208 12/10/2010 4:46:19 AM
    Now with the above data I want to find "sla status". Below is the condition:
    1. if datatime is 20101212 (yyyymmdd) and if sla is met on or before 20101212 6pm then it has to print sla status as "MET", by any chance if sla is met after 6pm then it has to print as "Not Met".
    2. So we dont have any static data in table and we have around 20k rows in the table.
    3. Datatime is a Number column.
    Please help me on this. ThanksDatatime is a number column? {noformat}*shudders*{noformat} Why?! Why is it not just DATE format? What's the difference between 20100101 and 20091231? 1 day if we're talking dates and 8870 if we're talking numbers. By taking out the fact that you're talking about dates in that column, you restrict the information available to the optimizer, and you open yourself up to poorly performing SQL.
    As it is, if you're looking to check the sla met time is before 6pm on the datatime, then you need to have a case statement, convert the datatime to a date (to_date() ) and then add 18 hours to that time and compare it with the sla_met_time.

  • Help with select into please

    Good morning everyone,
    I have a problem with my function. I need to do the dynamic select with the SELECT INTO
    create or replace function prueba (p_param IN VARCHAR2) RETURN VARCHAR2
    IS
    v_aux1 VARCHAR2(200);
    v_aux2 VARCHAR2(200);
    BEGIN
    SELECT col1
    INTO v_aux1
    FROM my_table
    WHERE col2 = p_param; --UNION SELECT '1233' FROM DUAL;
    RETURN v_aux1;
    EXCEPTION
    WHEN OTHERS THEN
    RAISE_APPLICATION_ERROR(-20000,SQLERRM );
    --RETURN v_aux2;
    END;
    When I try to call my function with the golden as follows:
    select (prueba('''MON'' UNION SELECT '||chr(039)||'12'||chr(039)||' FROM DUAL')) from dual
    OR
    select (prueba(chr(039)||'MON'||chr(039)||' UNION SELECT '||chr(039)||'12'||chr(039)||' FROM DUAL')) from dual
    I get the error: no data found
    If I use the sentence in Golden or SQLPLUS as follows:
    SELECT col1
    -- INTO aux1
    FROM my_table
    WHERE despaise = 'MON' UNION SELECT '12' FROM DUAL
    It ´s correct, and it return '1233'
    The value 'MON' no exists in my_table.
    If uncommented the sentence "UNION SELECT '1233' FROM DUAL" in my function an I use 'MON' as parameter it´s correct.
    How I can do this using the parameter with the UNION?.
    Thank you very much to all and sorry for my english

    Hi,
    welcome to the forum.
    Please read SQL and PL/SQL FAQ
    When you put some code or output please enclose it between two lines starting with {noformat}{noformat}
    i.e.:
    {noformat}{noformat}
    SELECT ...
    {noformat}{noformat}
    you cannot pass static SQL as part of the string.
    When you call the procedure in either wayselect (prueba('''MON'' UNION SELECT '||chr(039)||'12'||chr(039)||' FROM DUAL')) from dual
    select (prueba(chr(039)||'MON'||chr(039)||' UNION SELECT '||chr(039)||'12'||chr(039)||' FROM DUAL')) from dual
    This result in passing a whole string to your function as'MON' UNION SELECT '12' FROM DUAL
    which translates in your code asSELECT col1
    INTO v_aux1
    FROM my_table
    WHERE col2 = '''MON'' UNION SELECT ''12'' FROM DUAL'
    So it is searching a rows having col2 with value  '''MON'' UNION SELECT ''12'' FROM DUAL'
    Please try to explain what you are trying to achieve and we may help you.
    You could use dynamic SQL to do that but it is not clear what are your business requirement and the approach that you are using does not seem to be correct.
    Regards.
    Al                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Need guidance in where caluse of a select query.Please suggest.

    Hi All,
    I have a internal table IT_INPUT which includes multiple cost centers . Now for all entries in IT_INPUT-COst center i want to selct the records from COP table. The issue i am fasing is - Cost center is concatenated with some other values and stored in OBJNR field of COSP table like ex KSSPS1SF518 (SF518 is a cost center here, thease fields are of variable lenth)
    ex :
      SELECT objnr gjahr wrttp versn kstar wkf001 wkf002 wkf003 wkf004
             wkf005 wkf006 wkf007 wkf008 wkf009 wkf010 wkf011 wkf012
             FROM cosp INTO TABLE it_cosp
             FOR ALL ENTRIES IN it_input
          where objnr?
    what should we give in where claue. please suggest
    Thanks,
    Ravi

    You can use the code  a little modification of a above code...
    we will concatenate 2 * before and after the cost center. this will allow us to get the right result
    check it and let me know
    data:lr_objnr type range of cosp-objnr.
    data:wa like line of lr_objnr.
    wa-option = 'CP'.
    wa-sign = 'I'.
    Concatenate '*'
                         'SFS18' <cost center>
    INTO wa-low.
    append wa to lr_objnr.
    SELECT objnr gjahr wrttp versn kstar wkf001 wkf002 wkf003 wkf004
    wkf005 wkf006 wkf007 wkf008 wkf009 wkf010 wkf011 wkf012
    FROM cosp INTO TABLE it_cosp
    FOR ALL ENTRIES IN it_input
    where objnr in lr_objnr.

  • Help with one query ( Please reply)

    Oracle version : 11.2.0.2.0
    I have a table with the following set of rows
    with Table_dm AS
    ( select 1 month_no ,'wk1' week, 120 DM_AMT,300 GRoss_Amt,4 Week_no, 12 Gross_qty,1000 dm_adj_total from dual
      UNion all
      select 1 month_no ,'wk2' week,120 DM_AMT,300 GRoss_Amt,4 Week_no, 12 Gross_qty,1000 dm_adj_total from dual
      union all
      select 1 month_no ,'wk3' week,120 DM_AMT,300 GRoss_Amt,4 Week_no, 12 Gross_qty,1000 dm_adj_total from dual
      union all
      select 1 month_no ,'wk4' week,120 DM_AMT,300 GRoss_Amt,4 Week_no, 12 Gross_qty,1000 dm_adj_total from dual
      union all
      select 2 month_no ,'wk5' week,200 DM_AMT,400 GRoss_Amt,5 Week_no, 20 Gross_qty,1000 dm_adj_total from dual
      UNion all
      select 2 month_no ,'wk6' week,200 DM_AMT,400 GRoss_Amt,5 Week_no, 20 Gross_qty,1000 dm_adj_total from dual
      union all
      select 2 month_no ,'wk7' week,200 DM_AMT,400 GRoss_Amt,5 Week_no, 20 Gross_qty,1000 dm_adj_total from dual
      UNion all
      select 2 month_no ,'wk8' week,200 DM_AMT,400 GRoss_Amt,5 Week_no, 20 Gross_qty,1000 dm_adj_total from dual
      UNion all
      select 2 month_no ,'wk9' week,200 DM_AMT,400 GRoss_Amt,5 Week_no, 20 Gross_qty,1000 dm_adj_total from dual
    So the data in Grid  will be like this
    month_no
    week
    DM_AMT
    GRoss_Amt
    Week_no
    Gross_qty
    dm_adj_total
    DM_ADJ_Final
    1
    wk1
    120
    300
    4
    12
    1000
    1000 * 300 /(300+400) = 428.57
    =1
    wk2
    120
    300
    4
    12
    1000
    1000 * 300 /(300+400) = 428.57
    1
    wk3
    120
    300
    4
    12
    1000
    1000 * 300 /(300+400) = 428.57
    1
    wk4
    120
    300
    4
    12
    1000
    1000 * 300 /(300+400) = 428.57
    2
    wk5
    200
    400
    5
    20
    1000
    1000 * 400 /(300+400) = 571.42
    2
    wk6
    200
    400
    5
    20
    1000
    1000 * 400 /(300+400) = 571.42
    2
    wk7
    200
    400
    5
    20
    1000
    1000 * 400 /(300+400) = 571.42
    2
    wk8
    200
    400
    5
    20
    1000
    1000 * 400 /(300+400) = 571.42
    2
    wk9
    200
    400
    5
    20
    1000
    1000 * 400 /(300+400) = 571.42
    I need to calculate DM_ADJ_Final  where calculation for DM_ADJ_Final  will be like
                        = dm_adj_total * gross_amt/ (gross_amt (where month_no =1 ) + gross_amt (where month_no =2 )) ( Please refer  DM_ADJ_Final column above  for calculation with value )

    You apparently have (or intend) an association between rows where month_no = 1 and month_no = 2.
    But what is that relationship?  Is the month 2 row always 4 weeks later than the month 1 row?
    That relationship needs to be spelled out exactly.
    month_no
    week
    DM_AMT
    GRoss_Amt
    Week_no
    Gross_qty
    dm_adj_total
    DM_ADJ_Final
    1
    wk1
    120
    300
    4
    12
    1000
    1000 * 300 /(300+400) = 428.57
    =1
    wk2
    120
    300
    4
    12
    1000
    1000 * 300 /(300+400) = 428.57
    1
    wk3
    120
    300
    4
    12
    1000
    1000 * 300 /(300+400) = 428.57
    1
    wk4
    120
    300
    4
    12
    1000
    1000 * 300 /(300+400) = 428.57
    2
    wk5
    200
    400
    5
    20
    1000
    1000 * 400 /(300+400) = 571.42
    2
    wk6
    200
    400
    5
    20
    1000
    1000 * 400 /(300+400) = 571.42
    2
    wk7
    200
    400
    5
    20
    1000
    1000 * 400 /(300+400) = 571.42
    2
    wk8
    200
    400
    5
    20
    1000
    1000 * 400 /(300+400) = 571.42
    2
    wk9
    200
    400
    5
    20
    1000
    1000 * 400 /(300+400) = 571.42
    I need to calculate DM_ADJ_Final  where calculation for DM_ADJ_Final  will be like
                        = dm_adj_total * gross_amt/ (gross_amt (where month_no =1 ) + gross_amt (where month_no =2 )) ( Please refer  DM_ADJ_Final column above  for calculation with value )

  • Help with this query please

    Hi there, 
    These are the sample values
    declare @table table
    Name varchar(50),
    flag int
    insert into @table
    values('Matt', 0),
    ('George', 0),
    ('George', 1),
    ('Lucas', 0),
    ('Jerome', 0),
    ('Jerome', 1)
    I want to select out where George and Jerome where flag = 0 but leave the records from the same names where flag = 1. All others that only have flag = 0, should stay. So only the names that repeat and have both flag, flag = 0 zero should be selected out.
    Thanks for your help.

    So desired output is ????
    George 0
    Jerome 0
    declare @table table
    Name varchar(50),
    flag int
    insert into @table
    values('Matt', 0),
    ('George', 0),
    ('George', 1),
    ('Lucas', 0),
    ('Jerome', 0),
    ('Jerome', 1)
    select name,min(flag) flag,count(*) from @table
    group by name
    having count(*)>1
    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

  • Help in a query please

    POs PRs
    po1 r1
    po1 r1
    po1 r1
    po1 r1
    po2 r1
    po2 r3
    po2 r4
    po2 r4
    From the above two columns (POs, PRs) table I want the result where for same 'poX' print only if it has different 'rX'
    POs PRs
    po2 r1
    po2 r3
    po2 r4
    po2 r4
    So it should not print those POx if it has same PRx.

    Hi,
    That sounds like a job for the analytic COUNT function.
    Here's one way:
    WITH     got_prs_cnt     AS
         SELECT  pos, prs
         ,     COUNT (DISTINCT prs)
                  OVER (PARTITION BY pos)     AS prs_cnt  -- See note below
         FROM    table_x
    SELECT     pos, prs
    FROM     got_prs_cnt
    WHERE     prs_cnt     > 1
    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. Include examples of special cases that you need to handle (e.g., 3 rows with the same pos, and 2 disinct prs values).
    Point out where the query above is producing the wrong results, and explain, using specific examples, how you get the right results from the given data in those places.
    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 May 2, 2013 6:40 AM
    Changed "PARTITIION" (with 2 consecutive I's) to "PARTITION", after OP

  • Select query is correct or not

    hai to all iam software trainee in core java
    i have doubt on select query please give gudiance
    select * from StudentDetails where Admnno=' "
    i connected my application with ms-access db using jdbc-odbc
    my question is i want retrieve data from ms-access so i use this select query is it correct or not
    because
    select * from StudentDetails this query working but it's working with where condition please help and try to understand my question
    In advanced
    thanks

    ("select * from StudentDetails where Admnno ='' "+Admnno+"'")Is Admnno a numeric or character field? Either way, that syntax looks wonky.
    For a numeric field:("select * from StudentDetails where Admnno = " + Admnno)and for a character field("select * from StudentDetails where Admnno = '" + Admnno + "'")db
    Use code tags to post codes -- [code]CODE[/code] will display asCODEOr click the CODE button and paste your code between the tags that appear.

  • Questions on the most efficient select query..

    What is the difference between the two select query & please explain y is the 2nd select query more efficient??
    DATA: MAX_MSGNR type t100-msgnr.
    MAX_MSGNR = '000'.
    SELECT * FROM T100 INTO T100_WA
      WHERE SPRSL = 'D' AND
            ARBGB = '00'.
      CHECK: T100_WA-MSGNR > MAX_MSGNR.
      MAX_MSGNR = T100_WA-MSGNR.
    ENDSELECT.
    DATA: MAX_MSGNR type t100-msgnr.
    SELECT MAX( MSGNR ) FROM T100 INTO max_msgnr
      WHERE SPRSL = 'D' AND
            ARBGB = '00'.

    Hi,
    First never use Check statement in the Select.
    Next thing Select ... end select.
    Coming to ur question In case of first select it will fetch each record from the data base and compares that record value with the variable(MAX_MSGNR) and assigns the value to the variable. And this process will continue till the select reads all the records of the data base. Also these operations happens on the data base server. SO this query not only affect ur program but also others who is accessing the same data base.
    Second query is most efficient because of the aggregate function MAX. Here it will fetch all the records in single go and checks the max value for that column using
    optimising algorithm. So number of checks, assignments(single assignment) and fetches will be less compared to first select. This is the main reason. Hope this clarified ur doubt.
    Another thing is in first query we are selecting all the fields where as in second we are selecting only one field(required)
    Thanks,
    Vinod.
    Edited by: Vinod Kumar Vemuru on Mar 13, 2008 4:55 PM

Maybe you are looking for

  • How do I share a Keynote presentation when iWork ceases?

    My keynote presentation is enormous so e-mailing is not really an option, the recipient is new to all things iPad, so what is the easiest way to share a presentation? I know I can upload it to my computer but that seems unweildy. If they are ditching

  • My accelerometer(gravity sensor) doesn't work

    my ipod touch 4 accelerometer(gravity sensor) doesn't work, it has no response when i play games, watch video or photos,browsing web.....i update and restore many times...but still doesn't work... also,once i lock the ipod,it can't be unlock and rema

  • CFLDAP Avtive Directory Issues

    OK, so I searched but didnt find muchon the topic. Here is what Im trying to do: I need to find out if a user is part of a group called DMS_reset If the user is part of DMS_reset group then I plan on running a script that will allow themt o reset our

  • Adding zeros to a variable..

    I hav ea program that manipulates/works on six digit number entered by user.what i want is that if user enters less than 6 digits, program adds zeros at the end of number to make it 6 digit. like if user enters 241 program converts it into 241000 bef

  • HT4946 Problems when updating

    After updating to iOS 7.0.4 the phone wants to set up. I choose I-tunes, it syncronises but then nothing else happens. I can't reach anything, I can't pass this step even though I can see at my computer that it syncronises. Hope someone knows what to