SELECT-CASE in query

I have not used queries which use 'SELECT-CASE' but i have seen a query like as below:-
SELECT /*+ rule */ SUM(CASE WHEN age <= 15 THEN cnt ELSE 0 END) "upto 15 Years" ,
SUM(CASE WHEN age >= 16 AND age <= 20 THEN cnt ELSE 0 END) "16-20 Years" ,
SUM(CASE WHEN age >= 21 AND age <= 25 THEN cnt ELSE 0 END) "21-25 Years" ,
SUM(CASE WHEN age >= 26 AND age <= 30 THEN cnt ELSE 0 END) "26-30 Years" ,
SUM(CASE WHEN age >= 31 AND age <= 35 THEN cnt ELSE 0 END) "31-35 Years" ,
SUM(CASE WHEN age >= 36 AND age <= 40 THEN cnt ELSE 0 END) "36-40 Years" ,
SUM(CASE WHEN age >= 41 AND age <= 45 THEN cnt ELSE 0 END) "41-45 Years" ,
SUM(CASE WHEN age >= 46 AND age <= 50 THEN cnt ELSE 0 END) "46-50 Years" ,
SUM(CASE WHEN age >= 51 AND age <= 55 THEN cnt ELSE 0 END) "51-55 Years" ,
SUM(CASE WHEN age >= 56 AND age <= 60 THEN cnt ELSE 0 END) "56-60 Years" ,
SUM(CASE WHEN age >= 61 AND age <= 65 THEN cnt ELSE 0 END) "61-65 Years" ,
SUM(CASE WHEN age >= 66 AND age <= 70 THEN cnt ELSE 0 END) "66-70 Years" ,
SUM(CASE WHEN age > 70 THEN cnt ELSE 0 END) ">70 Years"
FROM
(SELECT /*+ rule */ROUND(MONTHS_BETWEEN(SYSDATE,ca.birthdate)/12) age,COUNT(1) cnt
FROM contract_all co , customer_all ca ,curr_co_status curr
WHERE ca.customer_id = co.customer_id
AND co.co_id = curr.co_id
AND curr.ch_status = 'a'
AND ca.birthdate IS NOT NULL
--AND    co.co_activated BETWEEN '01-jan-2004' AND  '31-dec-2004'
AND EXISTS ( SELECT 'x' FROM hss_cust_segment hcs
WHERE hcs.prgcode = ca.prgcode
AND hcs.description = 'POST')
GROUP BY ROUND(MONTHS_BETWEEN(SYSDATE,ca.birthdate)/12))
Please tell a bit, how this works.
I hope, my question is clear. Please help in solving the doubt.
Regards.

CASE statement works the same way as DECODE except that the later cannot use an operator. Think of CASE statement as having an IF...THEN...ELSE statement in you SELECT predicates.

Similar Messages

  • Select case with query

    Hello experts.
    i'm in sales offer > table OQUT.
    It is possible to have a FMS that select a query depending the OQUT.cardcode??
    E.G.
    if cardcode is A then run query A
    else cardcode is B then run query B
    i try this query :
    SELECT CASE  $[OQUT.cardcode]
    when '+MASTERFD'  Then
    select a.itemcode, a.price, c.itmsgrpnam
    from
         itm1 a
         inner join oitm b on a.itemcode = b.itemcode
         inner join oitb c on b.itmsgrpcod = c.itmsgrpcod
    where
    a.pricelist = (select listnum from ocrd where cardcode = $[OQUT.CardCode]) and
    c.itmsgrpnam = $[OQUT.U_JDT_OFF_MER] and
    (a.price <> 0 and a.price is not null)
    for browse
    else
    select a.itemcode, c.itemname, a.price, a.fromdate, a.todate, d.itmsgrpnam, a.linenum
    from spp1 a inner join
         (select cardcode, itemcode, max(todate) as ultimo from spp1 group by cardcode, itemcode) b
         on a.cardcode = b.cardcode and a.itemcode = b.itemcode and a.todate = b.ultimo
    inner join oitm c on a.itemcode = c.itemcode
    inner join oitb d on c.itmsgrpcod = d.itmsgrpcod
    where a.cardcode = $[$4.0]
    end
    Than's in advence...
    And sorry for my english....

    Hi Istvan...
    The query run in this mode:
    If  $[OQUT.cardcode]='+MASTERFD'
    select a.itemcode, a.price, c.itmsgrpnam
    from
         itm1 a
         inner join oitm b on a.itemcode = b.itemcode
         inner join oitb c on b.itmsgrpcod = c.itmsgrpcod
    where
    a.pricelist = (select listnum from ocrd where cardcode = $[OQUT.CardCode]) and
    c.itmsgrpnam = $[OQUT.U_JDT_OFF_MER] and
    (a.price != 0 and a.price is not null)
    else
    select a.itemcode, c.itemname, a.price, a.fromdate, a.todate, d.itmsgrpnam, a.linenum
    from spp1 a inner join
         (select cardcode, itemcode, max(todate) as ultimo from spp1 group by cardcode, itemcode) b
         on a.cardcode = b.cardcode and a.itemcode = b.itemcode and a.todate = b.ultimo
    inner join oitm c on a.itemcode = c.itemcode
    inner join oitb d on c.itmsgrpcod = d.itmsgrpcod
    where a.cardcode = $[OQUT.cardcode]]
    Thank you a lot...

  • Select list from query in report

    Hello everybody,
    I want to include a select list from a query in a report's colomn, but the select list should only be displayed conditionally. I wanted to do this with the help of "case when" in the corresponding SQL statement.
    The select list itsself works, but when I combine it with "case when" I always get the error message:
    ORA-01427: single-row subquery returns more than one row
    The select statement is as following:
    select
    htmldb_item.checkbox(1,rownum) " ",
    x.idee,
    x.stunden_ilp,
    x.stunden_ild,
    x.stunden_ilm,
    x.stunden_ief,
    x.stunden_ir,
    x.pe_id,
    x.l_art_id,
    x.version_id
    from (
    select
    (select case
    when (select name from cn_pl_projektidee s01
    where s01.idee_id = '2') IS NULL then
    (select distinct htmldb_item.select_list_from_query(5,name,'select distinct name from cn_pl_projektidee') name from cn_pl_projektidee s01
    where s01.idee_id = t1.idee_id)
    else
    (select distinct htmldb_item.text(5,name) name from cn_pl_projektidee s01
    where  s01.idee_id = t1.idee_id)
    END from cn_pl_std_peplanung t1) Idee,
    from cn_pl_std_peplanung t1, cn_pl_projektelemente z1, cn_pl_version u1, cn_pl_projektidee s1
    where t1.version_id = '&P6_VERSION_WAHL.'
    and t1.pe_id ='&P6_HELP_PRODET.' 
    and t1.l_art_id ='&P6_L_ART_ID.'
    group by t1.pe_id, t1.version_id, t1.idee_id, t1.l_art_id) x
    order by x.ideeDoes anybody know what could be the problem or what other solutions I could try??
    Greetings!
    Patrick

    Found 2 ways to solve it:
    *1. dynamic action (JQuery)*
    $("#f20_1234 option[value=13]").attr('selected', 'selected');
    *2. process*
    BEGIN
    HTP.p('<script type="text/javascript">');
    --HTP.p('problem()');
    HTP.p('html_SetSelectValue(''f20_903'',188)');
    HTP.p('html_SetSelectValue(''f20_903'',189)');
    HTP.p('</script>');
    END;

  • Display select list from query on manual tabular form

    Hello,
    I'm trying to display a select list from query on a manual tabular form. I'm using a collection to store the data. I can't seem to get the query to work. I can display the item as a text item. Any help would be appreciated. Thanks, Elizabeth.
    SELECT
    -- Notice how I'm keeping the idx value the same as the column value in the collection. This helps to keep things organized
    -- I also apply an id to each entry
    -- I append the error value to the empname and sal
    -- The Seq_id. Usefull when hiding rows (for delete) and then submitting from
    apex_item.hidden(1,x.seq_id, null, x.seq_id || '_seq_id') ||
    -- The Primary Key of the column
    apex_item.hidden(2, x.ceah_people_id, null, x.seq_id || '_ceah_people_id') || x.ceah_people_id ceah_people_id,
    -- Employee Name
    case when x.seq_id = -1
    then
    apex_item.select_list_from_query (3,
    NULL,
    'select distinct language_name d, '
    || 'language_id r from foreign_language',
    'style="width:170px" ' ,
    'YES',
    '0',
    '- Select Language -',
    'x.seq_id_' || LPAD (9900 + LEVEL, 4, '0'),
    NULL,
    'NO'
    else
    apex_item.text (3,(select language_name from foreign_language where x.language_id = foreign_language.language_id),
    80,
    100,
    'style="width:170px" readonly="readonly"',
    'f32_' || LPAD (ROWNUM, 4, '0')
    end
    || err.language_id language_id,
    /* apex_item.text(3,x.language_id,null, null, null, x.seq_id || '_language_id') || err.language_id language_id,
    -- Employee Salary
    apex_item.text(4,x.proficiency, null, null, null, x.seq_id || '_proficiency') || err.proficiency ||
    -- Store the sql action type as well.
    apex_item.hidden(50,x.sql_action_typ, null, x.seq_id || '_sql_action_typ_id') proficiency,
    -- Last but not least the row error
    err.row_error
    FROM (SELECT ac.c001 seq_id,
    ac.c002 ceah_people_id,
    ac.c003 language_id,
    ac.c004 proficiency,
    ac.c049 modifiable_flag,
    ac.c050 sql_action_typ
    FROM apex_collections ac
    WHERE ac.collection_name = 'DATA_COLLECTION'
    ORDER BY ac.seq_id) x,
    -- Error Collection
    (SELECT ac.seq_id seq_id,
    ac.c002 ceah_people_id,
    ac.c003 language_id,
    ac.c004 proficiency,
    ac.c050 row_error -- Useful when individual data is correct, however the row of data is not. Ex: start/end dates
    FROM apex_collections ac
    WHERE ac.collection_name = 'ERROR_COLLECTION'
    ORDER BY ac.seq_id) err
    WHERE x.seq_id = err.seq_id(+)

    I got so frustrated I started over. I'm following the how to create a manual form.
    http://www.oracle.com/technology/products/database/application_express/howtos/tabular_form.html#MANUAL
    The problem I'm now having is even though I display items as hidden, there is a column holder on the report for them. If I go into the report attributes and toggle the show attribute off I cannot reference an items value in my logic. I used /&nbsp/ for the column heading but I still get the little sort arrow where the column heading should be. I tried to toggle the sort attribute off but the sort arrow still shows up. How can I use the apex_item.hidden and not get a place holder for the column on a report? Thanks, Elizabeth
    Here is the code I'm using to generate the report:
    select x.ceah_people_lang_id,
    x.language_id,
    x.proficiency,
    x.ceah_people_id
    from (
    select apex_item.hidden(1,ceah_people_lang_id) ceah_people_lang_id,
    apex_item.select_list_from_query(2,language_id,'select language_name, language_id from foreign_language') language_id,
    apex_item.select_list_from_query(3,proficiency,'select name, id from proficiency') proficiency,
    apex_item.hidden(4,ceah_people_id) ceah_people_id
    from ceah_people_language where ceah_people_language.ceah_people_id = :P152_person_id
    union all
    select apex_item.hidden(1,null) ceah_people_lang_id,
    apex_item.select_list_from_query(2,null,'select language_name, language_id from foreign_language') language_id,
    apex_item.select_list_from_query(3,null,'select name, id from proficiency') proficiency,
    apex_item.hidden(4,null) ceah_people_id
    from dual) x

  • Can i use case in query in oracle form 6i

    sir can i use case in query in oracle form 6i
    such as
    select empno, case when deptno=10 then dptno end from emp;
    please gice me

    Hello,
    Does this code compile ?
    If not, I'm afraid that the PL/SQL engine of Forms6i does not recognize this syntax.
    Francois

  • Constant Selection in BEx Query Designer on BI7

    Hi guys
    According to this blog <a href="/people/prakash.darji/blog/2006/09/19/the-hidden-secret-of-constant-selection Selection</a>, we can create constant selection on both Characteristics and Key figures. I understand how to do it with restricted key figures.
    Can anyone give me a step by step guide on how to create constant selection for a Characteristic in BEx Query Designer on BI7. I can't find options for 'constant selection'
    Or is this the same thing when you include or exclude values?
    Message was edited by:
            jimi ogun

    Thanks Krishna
    I am actually using a Multiprovider for my queries but business requirements mean I need to create joins.
    I am trying to avoid Infosets and I believe another way is to use the Constant Selection feature in Query Designer.
    Going back to my previous posting, I know how this is done with a restricted KF but I don't know how when it comes to characteristics.
    Can anyone help?

  • Can anyone suggest a select case statement in place of my if statements?

    I am having a little trouble switching my if statements to select case. Any help would be appreciated
    Option Strict On
    Option Explicit On
    Public Class Form1
    Private Player1 As String
    Private Player2 As String
    Private Player1Wins As Integer = 1
    Private Player2Wins As Integer = 1
    Private Tie As Integer = 1
    ' Close the program
    Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
    Me.Close()
    End Sub
    ' ask for players names
    Private Sub frmMainForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Player1 = InputBox("Enter Player 1's Name: ")
    lblPlayer1.Text = (Player1 + "'s Score:")
    Player2 = InputBox("Enter Player 2's Name:")
    lblPlayer2.Text = (Player2 + "'s Score:")
    End Sub
    Private Sub btnRoll_Click(sender As Object, e As EventArgs) Handles btnRoll.Click
    ' game of rolling dice
    Dim randGen As New Random
    Dim intNum1 As Integer
    Dim intNum2 As Integer
    Dim intNum3 As Integer
    Dim intNum4 As Integer
    Dim intTotal As Integer
    Dim intTotal2 As Integer
    ' make random integer from 1 through 6
    intNum1 = randGen.Next(1, 7)
    intNum2 = randGen.Next(1, 7)
    intNum3 = randGen.Next(1, 7)
    intNum4 = randGen.Next(1, 7)
    ' display the right image in picDie1
    Select Case intNum1
    Case 1
    picDie1.Image = picOneDot.Image
    Case 2
    picDie1.Image = picTwoDots.Image
    Case 3
    picDie1.Image = picThreeDots.Image
    Case 4
    picDie1.Image = picFourDots.Image
    Case 5
    picDie1.Image = picFiveDots.Image
    Case 6
    picDie1.Image = picSixDots.Image
    End Select
    ' display the right image in picDie2
    Select Case intNum2
    Case 1
    picDie2.Image = picOneDot.Image
    Case 2
    picDie2.Image = picTwoDots.Image
    Case 3
    picDie2.Image = picThreeDots.Image
    Case 4
    picDie2.Image = picFourDots.Image
    Case 5
    picDie2.Image = picFiveDots.Image
    Case 6
    picDie2.Image = picSixDots.Image
    End Select
    ' display the right image in picDie3
    Select Case intNum3
    Case 1
    picDie3.Image = picOneDot.Image
    Case 2
    picDie3.Image = picTwoDots.Image
    Case 3
    picDie3.Image = picThreeDots.Image
    Case 4
    picDie3.Image = picFourDots.Image
    Case 5
    picDie3.Image = picFiveDots.Image
    Case 6
    picDie3.Image = picSixDots.Image
    End Select
    ' display the right image in picDie4
    Select Case intNum4
    Case 1
    picDie4.Image = picOneDot.Image
    Case 2
    picDie4.Image = picTwoDots.Image
    Case 3
    picDie4.Image = picThreeDots.Image
    Case 4
    picDie4.Image = picFourDots.Image
    Case 5
    picDie4.Image = picFiveDots.Image
    Case 6
    picDie4.Image = picSixDots.Image
    End Select
    ' calculate and display total number of dots
    intTotal = intNum1 + intNum2
    lblTotal.Text = intTotal.ToString()
    intTotal2 = intNum3 + intNum4
    lblTotal2.Text = intTotal2.ToString()
    ' display the winner
    If intTotal > intTotal2 Then
    MessageBox.Show("Player1 Wins")
    End If
    If intTotal2 > intTotal Then
    MessageBox.Show("Player2Wins")
    End If
    If intTotal = intTotal2 Then
    MessageBox.Show("Tie")
    End If
    ' display summary information when checkbox is checked
    If CheckBox1.Checked = True And
    intTotal > intTotal2 Then
    lblWins.Text = CStr(Player1Wins)
    Player1Wins = Player1Wins + 1
    lblScores.Visible = True
    End If
    If CheckBox1.Checked = True And
    intTotal2 > intTotal Then
    lblWins2.Text = CStr(Player2Wins)
    Player2Wins = Player2Wins + 1
    lblScores.Visible = True
    End If
    If CheckBox1.Checked = True And
    intTotal = intTotal2 Then
    lblTies.Text = CStr(Tie)
    Tie = Tie + 1
    lblScores.Visible = True
    End If
    End Sub
    End Class

    Put everything into lists. Here is elementary sample to get you started.
    Private lofDotImage As New List(Of Image)
    Private randGen As New Random
    Private picDie() As PictureBox
    Private Sub setup()
    ReDim picDie(3)
    picDie(0).Location = New Point()
    picDie(0).Size = New Size()
    picDie(1).Location = New Point()
    picDie(1).Size = New Size()
    picDie(2).Location = New Point()
    picDie(2).Size = New Size()
    picDie(3).Location = New Point()
    picDie(3).Size = New Size()
    For _delta As Integer = 0 To 3
    picDie(_delta).Visible = True
    Me.controls.add(picDie(_delta))
    Next _delta
    Dim _dice1 As Image = Nothing
    Dim _dice2 As Image = Nothing
    Dim _dice3 As Image = Nothing
    Dim _dice4 As Image = Nothing
    Dim _dice5 As Image = Nothing
    Dim _dice6 As Image = Nothing
    lofDotImage.Add(_dice1)
    lofDotImage.Add(_dice2)
    lofDotImage.Add(_dice3)
    lofDotImage.Add(_dice4)
    lofDotImage.Add(_dice5)
    lofDotImage.Add(_dice6)
    End Sub
    Private Sub roll()
    Dim _lofRolls As New List(Of Integer)
    Dim intScorePlayer1 As Integer = 0
    Dim intScorePlayer2 As Integer = 0
    For _delta As Integer = 0 To 3
    _lofRolls.Add(randGen.Next(1, 7))
    If _delta < 2 Then
    intScorePlayer1 += _lofRolls(_delta)
    Else
    intScorePlayer2 += _lofRolls(_delta)
    End If
    picDie(_delta).Image = lofDotImage(_lofRolls(_delta))
    Next _delta
    If intScorePlayer1 = intScorePlayer2 Then
    MessageBox.Show("Tie")
    ElseIf intScorePlayer1 > intScorePlayer2 Then
    MessageBox.Show("Player1 Wins")
    Else
    MessageBox.Show("Player2 Wins")
    End If
    End Sub
    Edit: Also to get better random, seed the random once and generate many times, the more seed is the less random.
    Also another tip: When comparing it is easy to check  = and <> compared to < or > in my experience, also for only one possible outcome use one main if block instead of many.

  • How to use multi select in a query report

    I defined a lov. This lov retuns name and a id. I want to use the result of this multi select in my query.
    I always get invalid number when I choose two items of the select. When I debug I see that the return value of the multi select is 1:2. How can I change the seperator : in , I tried the following but this does't work.
    if :P26_PRODUCTTYPE IS NOT NULL then
    l_sql := l_sql ||' and producttype in
    (REPLACE(:p26_producttype,'':'','','' ))';
    end if;

    as you're finding, multiple values selected from html db multi-select list items (and checkboxes) are stored as a single, colon-delimited string. i explained an easy way to handle this via pl/sql in...
    Multiple select list
    ...that post shows you how to throw the selected values into a pl/sql table and step through them as needed. it also showed how to use an instr to parse through the string if you want to go that route. you could use that same instr logic right in your sql query. so let's say your lov for your multi-select item (P1_MY_MULTISELECT, we'll call it) was defined as...
    select ename, empno from emp order by 1
    ...and your user selected KING, FORD, and JONES. :P1_MY_MULTISELECT would store those values as...
    7839:7902:7566
    ...you could then write a query to return the selected enames with something like...
    select ename, job
    from emp
    where insrt (':'||:P1_MY_MULTISELECT||':',':'||empno||':') != 0
    ...hope this helps,
    raj

  • Doubt in 'SELECT-CASE'

    I have a doubt in 'SELECT-CASE'. There is this example of which i have :-
    SELECT /*+ rule */ SUM(CASE WHEN age <= 15 THEN cnt ELSE 0 END) "upto 15 Years" ,
    SUM(CASE WHEN age >= 16 AND age <= 20 THEN cnt ELSE 0 END) "16-20 Years" ,
    SUM(CASE WHEN age >= 21 AND age <= 25 THEN cnt ELSE 0 END) "21-25 Years" ,
    SUM(CASE WHEN age >= 26 AND age <= 30 THEN cnt ELSE 0 END) "26-30 Years" ,
    SUM(CASE WHEN age >= 31 AND age <= 35 THEN cnt ELSE 0 END) "31-35 Years" ,
    SUM(CASE WHEN age >= 36 AND age <= 40 THEN cnt ELSE 0 END) "36-40 Years" ,
    SUM(CASE WHEN age >= 41 AND age <= 45 THEN cnt ELSE 0 END) "41-45 Years" ,
    SUM(CASE WHEN age >= 46 AND age <= 50 THEN cnt ELSE 0 END) "46-50 Years" ,
    SUM(CASE WHEN age >= 51 AND age <= 55 THEN cnt ELSE 0 END) "51-55 Years" ,
    SUM(CASE WHEN age >= 56 AND age <= 60 THEN cnt ELSE 0 END) "56-60 Years" ,
    SUM(CASE WHEN age >= 61 AND age <= 65 THEN cnt ELSE 0 END) "61-65 Years" ,
    SUM(CASE WHEN age >= 66 AND age <= 70 THEN cnt ELSE 0 END) "66-70 Years" ,
    SUM(CASE WHEN age > 70 THEN cnt ELSE 0 END) ">70 Years"
    FROM
    (SELECT /*+ rule */ROUND(MONTHS_BETWEEN(SYSDATE,ca.birthdate)/12) age,COUNT(1) cnt
    FROM contract_all co , customer_all ca ,curr_co_status curr
    WHERE ca.customer_id = co.customer_id
    AND co.co_id = curr.co_id
    AND curr.ch_status = 'a'
    AND ca.birthdate IS NOT NULL
    --AND    co.co_activated BETWEEN '01-jan-2004' AND  '31-dec-2004'
    AND EXISTS ( SELECT 'x' FROM hss_cust_segment hcs
    WHERE hcs.prgcode = ca.prgcode
    AND hcs.description = 'POST')
    GROUP BY ROUND(MONTHS_BETWEEN(SYSDATE,ca.birthdate)/12))
    In this the statements on top like this-
    SUM(CASE WHEN age >= 16 AND age <= 20 THEN cnt ELSE 0 END) "16-20 Years" ,
    how does the increment happen in 'THEN cnt' because we are not doing the increment as such using '+1' kind of thing.
    I hope, my question is clear. Please help in solving the doubt.
    Regards.

    Sample data, wrong output and desired output please...
    I tried with this and it seems right...
    WITH ca as (
      select to_date('26-9-1990') birthdate from dual union all
      select to_date('26-9-1989') birthdate from dual union all
      select to_date('26-9-1974') birthdate from dual
    SELECT /*+ rule */ SUM(CASE WHEN age <= 15 THEN cnt ELSE 0 END) "upto 15 Years" ,
      SUM(CASE WHEN age >= 16 AND age <= 20 THEN cnt ELSE 0 END) "16-20 Years" ,
      SUM(CASE WHEN age >= 21 AND age <= 25 THEN cnt ELSE 0 END) "21-25 Years" ,
      SUM(CASE WHEN age >= 26 AND age <= 30 THEN cnt ELSE 0 END) "26-30 Years" ,
      SUM(CASE WHEN age >= 31 AND age <= 35 THEN cnt ELSE 0 END) "31-35 Years" ,
      SUM(CASE WHEN age >= 36 AND age <= 40 THEN cnt ELSE 0 END) "36-40 Years" ,
      SUM(CASE WHEN age >= 41 AND age <= 45 THEN cnt ELSE 0 END) "41-45 Years" ,
      SUM(CASE WHEN age >= 46 AND age <= 50 THEN cnt ELSE 0 END) "46-50 Years" ,
      SUM(CASE WHEN age >= 51 AND age <= 55 THEN cnt ELSE 0 END) "51-55 Years" ,
      SUM(CASE WHEN age >= 56 AND age <= 60 THEN cnt ELSE 0 END) "56-60 Years" ,
      SUM(CASE WHEN age >= 61 AND age <= 65 THEN cnt ELSE 0 END) "61-65 Years" ,
      SUM(CASE WHEN age >= 66 AND age <= 70 THEN cnt ELSE 0 END) "66-70 Years" ,
      SUM(CASE WHEN age > 70 THEN cnt ELSE 0 END) ">70 Years"
    FROM ( SELECT /*+ rule */ ROUND(MONTHS_BETWEEN(SYSDATE,ca.birthdate)/12) age, COUNT(1) cnt
           FROM ca
           GROUP BY ROUND(MONTHS_BETWEEN(SYSDATE,ca.birthdate)/12) )
    upto 15 Years          16-20 Years            21-25 Years            26-30 Years            31-35 Years            36-40 Years            41-45 Years            46-50 Years            51-55 Years            56-60 Years            61-65 Years            66-70 Years            >70 Years             
    0                      2                      0                      0                      1                      0                      0                      0                      0                      0                      0                      0                      0                     
    1 rows selectedNH.

  • Using a scalar user defined function in a select case statement

    I have a simple select statement below and I want to have a case statement for some conditions based on the result of the udf returned value. I then want the returned value from that specific case statement to be returned where i have indicated 'DISPLAY
    ZIPCODE' below.
    SELECT
        CASE
             WHEN (SELECT Top 1 ZipCode FROM ufn_GetAddressByBusinessEntityIDandAddressTypeID(table1.BusinessEntityID,712) IS NOT NULL THEN 'DISPLAY ZIPCODE'
             WHEN (SELECT Top 1 ZipCode FROM ufn_GetAddressByBusinessEntityIDandAddressTypeID(table1.BusinessEntityID,714) as r) IS NOT NULL THEN 'DISPLAY ZIPCODE'
             ELSE NULL
           END as Zipcode,
    FROM
    table1

    SELECT COALESCE(ufn_GetAddressByBusinessEntityIDandAddressTypeID(table1.BusinessEntityID,712),ufn_GetAddressByBusinessEntityIDandAddressTypeID(table1.BusinessEntityID,712)) AS Zipcode
      FROM table1
    Nope. This is two function calls. coalesce(a, b, c, ...) is just syntatic sugar for
       CASE WHEN a IS NOT NULL THEN a
            WHEN b IS NOT NULL THEN b
            WHEN c IS NOT NULL THEN c
       END
    But if you use isnull it's a different matter. (But isnull() permits two arguments.)
    Erland Sommarskog, SQL Server MVP, [email protected]

  • How to put variable selection and the query result the same screen

    Dear all,
       how can I put the variable selection and the query result in the same screen? Please advise. Thanks.
    Jin Ming

    Not sure if you are saying you want the prompts on the same page as the results... however in 7.0 with BEx Analyzer, you can insert a text object from the design toolbar and assign it to the variable.... this way, lets say you run query for period 6, then the text object will display "6" on the same area where the query results are.

  • Function with select if statement query

    Hi,
    I want to use if condition in select statement in function.
    But i implemented in case too ,its taking more time to return the value while using case statement.
    My function is like this
    create or replace FUNCTION GET_CODE
    (pv_type IN table1.type%TYPE,
    pv_desc1 IN table2.type%TYPE,
    pv_desc2 IN table3.type%TYPE)
    RETURN varchar2(35 byte)
    IS
    V_ret_string varchar2(35 byte);
    BEGIN
    SELECT case when(table2.xxx like 'fff%') then 1
    when (table3.yyy like 'fff%') then 2
    when (table4.zzz like 'fff%') then 3
    else table1.aaa
    INTO V_ret_string
    FROM
    table1 a,table2 b,table3 c table4 d
    WHERE
    table1.column1=table2.column1
    and (table1.column2=table3.column1 or table1.column2=table4.column1) and
    UPPER(b.type) = UPPER(pv_type) and
    (UPPER(c.desc) = UPPER(pv_desc1) or UPPER(d.desc1) = UPPER(pv_desc2)) ;
    RETURN V_ret_string;
    END GET_TRANSACTION_CODE;
    Pls help me how to use if condition.
    Regards,
    Punitha

    936698 wrote:
    Hi,
    I want to use if condition in select statement in function.Oracle SQL SELECT statement does not support IF condition syntax. But what it does is CASE and DECODE. And CASE statement is sufficient to achieve what ever you want to do with IF condition.
    But i implemented in case too ,its taking more time to return the value while using case statement.So the issue is not with CASE its with the SELECT Statement. What you have to do is Isolate your SELECT statement and try to tune it for performance.
    To do that i would suggest you to read the folloing threads which could be of good use.
    {thread:id=501834} and {thread:id=863295}.
    >
    >
    My function is like this
    create or replace FUNCTION GET_CODE
    (pv_type IN table1.type%TYPE,
    pv_desc1 IN table2.type%TYPE,
    pv_desc2 IN table3.type%TYPE)
    RETURN varchar2(35 byte)
    IS
    V_ret_string varchar2(35 byte);
    BEGIN
    SELECT case when(table2.xxx like 'fff%') then 1
    when (table3.yyy like 'fff%') then 2
    when (table4.zzz like 'fff%') then 3
    else table1.aaa
    INTO V_ret_string
    FROM
    table1 a,table2 b,table3 c table4 d
    WHERE
    table1.column1=table2.column1
    and (table1.column2=table3.column1 or table1.column2=table4.column1) and
    UPPER(b.type) = UPPER(pv_type) and
    (UPPER(c.desc) = UPPER(pv_desc1) or UPPER(d.desc1) = UPPER(pv_desc2)) ;
    RETURN V_ret_string;
    END GET_TRANSACTION_CODE;When ever posting code please make sure the code is well formatted and you use the {noformat}{noformat} tag to preserve the format. An unformatted code is very hard to read.
    The usage of the tag is like this.
    <place your code here>\                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • SELECT CASE IN PL/SQL

    I NEED TO KNOW HOW TO RUN IN PL THE STATEMENT select case
    when ...
    thanks

    Hi
    SELECT with a CASE statement will not work in 8i when using
    static SQL. However if you are using dynamic SQL to execute it,
    then it will be fine. This is because the dynamic SQL statement
    is passed to the SQL engine for executing wheras static SQL is
    compiled by the PL/SQL compiler, which does not understand the
    complete SQL syntax.
    This will be fixed in 9i as well as PL/SQL in 9i also includes
    the CASE statement itself (outside of SQL).
    Guido

  • When to use SELECT and END SELECT in the query.

    hi all,
    When to use SELECT and END SELECT in the query.
    regads,
    Venkata Suresh Penke.

    Hi Suresh..
    When do we need to use SELECT .. ENDSELECT
    Usually we will never use SELECT .. ENDSELECT as it gives very poor performance.
    But whenever we read a single Record we will use it as an alternative for SELECT SINGLE in some scenarios.
    Eg: When the Full primary key is not specified in the WHERE clause.
    SELECT * FROM MARC INTO WA_MARC UP TO 1 ROWS WHERE MATNR = P_MATNR.
    ENDSELECT.
    And other scenario is when we perform AGGREGATE OPERATIONS.when the Result is only one row.
    SELECT SUM( LABST ) FROM MARD INTO V_LABST UP TO 1 ROWS
    WHERE MATNR = P_MATNR.
    ENDSELECT.
    Note: In The Above scenario we cannot use SELECT SINGLE..
    <b>REWARD IF HELPFUL.</b>

  • Using function on decode or case in query

    Hi experts
    I am using oracle 11G database,I have to check length of name column value from employee table and if length(name) > 39 then value should be substr(name,0,39)
    else value should be name only.
    i tried below code
    select CASE when length(name) > 39,substr(name,0,39)
                else name
           END
      from employee but its not working ..can I do this using decode too ? ,,which one would be better or this is not a right way ?
    Thanks

    Hi,
    siebelD wrote:
    Hi experts
    I am using oracle 11G database,I have to check length of name column value from employee table and if length(name) > 39 then value should be substr(name,0,39)
    else value should be name only.
    i tried below code
    select CASE when length(name) > 39,substr(name,0,39)
    else name
    END
    from employee but its not working ..Review the syntax of the CASE expression in the SQL Language manual. A CASE expression always has at least one THEN clause. Commas are not part of the CASE expression syntax.
    can I do this using decode too ? Sure, anything you can do with CASE you can also do with DECODE.
    ,,which one would be betterThis is one of the many situations where CASE is much shorter, clearer and more efficient than DECODE.
    or this is not a right way ?How about
    SELECT  SUBSTR (name, 1, 39)  AS employee_name
    FROM    employee;?
    If name is 39 characters (or less), then <tt> SUBSTR (name, 1, 39) </tt> will return it, unchanged.
    Edited by: Frank Kulash on Mar 3, 2013 2:07 PM

Maybe you are looking for

  • Value of the previous cell when I double click a cell in ALV Grid.

    Hi ! Suppose I have an internal table GT_ITAB and I use ALV Grid to print it on the screen. The colums are as below: Invoice No       Invoice Data        Customer No     Amount   90001231        15.01.2009            100024             5 Customer No

  • Help required with upgrading to OS5 on curve 8520

    Hello everyone, I'm using an unlocked version of the bb curve 8520 and want to upgrade my bb device os to v5.0. (current version- 4.6.1) I tried using the application loader on the bb website (NA & India both) but it just tells me that my OS is updat

  • Can I convert from pdf output into excellsheet in smartforms

    My smartform output is in pdf form now .Can i convert it into excellsheet by using save option. Moderator message: please do some own research before asking. Edited by: Thomas Zloch on Feb 21, 2011 12:49 PM

  • Find and delete .DS_Store files

    I have a 2008 server where some mac clients connect. They create .DS_Store, ._.TemporaryItems and other files that starts with "._". I want to find them and delete them every night. What kind of script can I run. Thank you so much for your help.

  • Problem with javadoc

    I am facing problem when trying to generate javadoc for two packages under a same parent hierarchy.. when i give the following command D:\Projects\ABC>javadoc -d d:\Projects\ABC\docs com.common com.list where com.common com.list are two packages unde