IF Statement in Select

I need to choose between value1 and value2 within a select statement.
TableA
Flag (char)
Value1
Value2
ItemDesc
pseudo code
select ItemDesc, (if Flag = 'y' then Value1 else Value2) as Price from TableA;
How can this be done?

select   itemdesc,
         sum (case
                 when flag = 'y'
                    then (case
                             when value1 < 10
                                then value1 * 1.2
                             else value1
                          end)
                 else value2
              end
             ) as price
    from tablea
group by itemdesc;

Similar Messages

  • Alter Statement in Select

    Can we write an alter statement in Select Query?

    Dynamic sql
    SQL> create table t_al (al number(10));
    Table created.
    SQL>
    DECLARE
       v_al   VARCHAR2 (200);
    BEGIN
        select 'alter table t_al modify al varchar2(20)' into v_al from dual;
    execute immediate v_al;
    end;
    PL/SQL procedure successfully completed.
    SQL> desc t_al;
      AL  VARCHAR2(20 CHAR)

  • In a SQL statement, the SELECT clause is used to

    In a SQL statement, the SELECT clause is used to select
    (a) columns
    (b) rows
    (c) tables
    (d) none of the above
    can any one help Immediately

    Is used to select rows of specified column...
    SELECT column_name(s) FROM table_name

  • How to convert update,delete statement into select stmt

    Hi all,
         I have a field called dml_stmt, i am getting the dml statement has input from the user.
         My requirement is, if user is giving "update set col_name = 'xyz' from table_name where codition = 'aa'", before updating the table, i need to get old values from the table and put it in the audit table
         For that,i need to convert those update statement into select stmt and need to execute the query to get the data and then i will put it in the audit table..
         can anyone guide how to convert the update or delete stmt into select(need to write in pl/sql)
    Please do needfull things ......
    Regards,
    Jame

    Maybe I'm missing something, but why would auditing help here? It sounds like the user wants to know the prior values of the data, not the SQL UPDATE statement that was issued. Auditing would tell you that a table was updated, fine-grained auditing would tell you what the UPDATE statement was, but you'd need something else to capture the state of the data prior to the update.
    Depending on why putting triggers on every table was discounted, you may also want to take a look at using Workspace Manager or Total Recall (in 11g) to track a history of data changes. But triggers would be the common solution to this sort of problem.
    Justin

  • Difference between "print" statements and "select" statements , TSQL

     What is the difference between "print" statements and "select" statements when it omces to debugging and watching varibles in the stored procs .....

    SELECT statement is part of the ANSI SQL language.
    PRINT command is not part of the SQL language, it is used for debugging in T-SQL.
    BOL:" Returns a user-defined message to the client.
    A message string can be up to 8,000 characters long if it is a non-Unicode string, and 4,000 characters long if it is a Unicode string. Longer strings are truncated. The
    varchar(max) and nvarchar(max) data types are truncated to data types that are no larger than
    varchar(8000) and nvarchar(4000).
    RAISERROR can also be used to return messages. RAISERROR has these advantages over PRINT:
    RAISERROR supports substituting arguments into an error message string using a mechanism modeled on the printf function of the C language standard library.
    RAISERROR can specify a unique error number, a severity, and a state code in addition to the text message.
    RAISERROR can be used to return user-defined messages created using the sp_addmessage system stored procedure."
    LINK: http://technet.microsoft.com/en-us/library/ms176047.aspx
    The SSMS (client software) returns SELECT output to Results and PRINT output to Messages.
    The SQLCMD -o (output file) option captures all outputs into one file mixed.
    Kalman Toth Database & OLAP Architect
    T-SQL Scripts at sqlusa.com
    New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012

  • If statement in select statement alias

    I have the following select statement. It has the alias Survivors, Deaths and "All Cases". Is it posible to use :P_LANGUAGE variable to say that -- IF :P_LANGUAGE = FRENCH THEN alias are Survivants for survivors, Décès for Deaths, Tous_les_cas for All Cases. Please advise
    SELECT ALL T_NTR_MULTIBAR.CAT, T_NTR_MULTIBAR.NUM_CASES_LEFTBAR AS Survivors,
    T_NTR_MULTIBAR.NUM_CASES_MIDDLEBAR AS Deaths, T_NTR_MULTIBAR.NUM_CASES_RIGHTBAR AS "All Cases"
    FROM T_NTR_MULTIBAR
    WHERE INSTANCE_NUM = :P_INSTANCENUM
    order by ORDERS

    You may not be able to add this condition inside the SQL Statement. But you can add this condition outside the statement, if you're using PL/SQL...
    IF :p_language = french THEN
    SELECT ALL t_ntr_multibar.cat,
      t_ntr_multibar.num_cases_leftbar AS survivors,
      t_ntr_multibar.num_cases_middlebar AS deaths,
      t_ntr_multibar.num_cases_rightbar AS "All Cases"
    ELSE
    END IF;

  • Decode statement in Select line of a View Object Query

    I attempted to create a view object in expert mode with a customized query.
    The query had a decode statement in the select line of the query. The view
    object compiled correctly but gave an error when run.
    ex: select .... decode(CrpSchools.SCHOOLS_ID,null,CrpCustSchools.SCHOOL_NAME,CrpSchools.SCHOOL_NAME) SCHOOL_VALUE, ...
    from ....
    where ....
    The error was that school_value does not exist in the statement. I got the error when
    doing a vo.executeQuery().
    When I removed the decode statement everything worked correctly. Does anyone know if
    the decode statement cannont be used in the select line of a query in a view object?
    Or maybe I was linking the query column (SCHOOLS_ID) up to the view attribute (SCHOOL_VALUE) incorrectly in the
    Attribute Mappings tab of the VO wizard?

    There should be no problem using a DECODE() statement, provided that you've aliases the column as you have done.
    At design time, if you click on the (Test) button, does your query test ok?
    Are you by chance applying a custom where clause at runtime?
    If so, are you saying:
    setWhereClause("yourtable.column_alias = ?";
    or are you doing:
    setWhereClause("column_alias = ?";
    for an expert-mode query, you'll need to use the latter syntax.

  • "If, Then" Statements Driving Selection

    I am creating a price list/order form and need some help with "If, Then" statements and how their result drives a price selection.
    I have a product that is priced differently based on both how many is purchased and how many colors it has. My variables are (a) one, two, three or four colors, and (b) 10 to 500 pieces in six tiers (10-24, 25-49, 50-99, 100-249, 250-499, 500+).
    I want to autopopulate a price field based on the color number and the quantity, making the pricing foolproof and the total order amount automatically calculated.
    Here's my situation:
      - Field A is Number of Colors (let's say 1-color)
      - Field B is Quantity (let's say it's 23, putting us in the 10-24 tier pricing)
      - Field C is Unit Price (1-color @ 23 qty would be $76.63 each)
      - Field D is Total Price (23 x $76.63)
    My statement would look like the following, but I don't know how to structure this in the form fields or where to put the quantity or pricing table for the software to calculate B or C:
    If A is 1-color, and B is 23, then C is $76.63.
    My Field D calculation is pretty straight-forward (Field C x Field D) if I can figure out a way to determine Field C's value.
    Help!

    Have a look at these tutorials:
    http://acrobatusers.com/tutorials/conditional-execution
    http://acrobatusers.com/tutorials/how-to-do-not-so-simple-form-calculations
    If you still need help afterwards, post here again.

  • Dynamic From statement in select query and/or outer join not working

    Dear Experts, I have a select query where the select columns are dynamic, the where condition is also dynamic. It is of the below format:
    Select (dynamic columns) INTO <wa>
    FROM a inner join b on af1 = bf1
    inner join c on af2 = cf2......
    WHERE (dynamic conditios)
    ORDER BY ( dynamic sort condition).
    Now I have to include some tables (dynamically depending on the user input) in the inner join statement which will give description for the selected fields. And these database tables may or may no be empty. So in this case, my select query will not return any data if these tables are empty. And I dont want that.
    I tried using outer join for the extra tables but it gave me a runtime error. I also tried forming the inner join statement dynamically but it was not supporting.
    Kindly give me pointers.
    Thanks

    Hey thanks for the reply, but the problem is not solved.
    I am already using  ( fileds, value) like table in my where condition and the select statement was working properly.
    the problem is that now I have to include some tables in the join statement which can be empty and so i want to use Outer join.
    But I am getting a runtime error as below:
    Error analysis
        An exception occurred that is explained in detail below.
        The exception, which is assigned to class 'CX_SY_DYNAMIC_OSQL_SYNTAX', was not
         caught in
        procedure "ZATSCSNG_RFC_READ_TABLE" "(FUNCTION)", nor was it propagated by a
         RAISING clause.
        Since the caller of the procedure could not have anticipated that the
        exception would occur, the current program is terminated.
        The reason for the exception is:
        The running ABAP program wanted to execute a SELECT statement whose
        WHERE condition was (partly) specified dynamically. The part that is
        specified in an internal table at runtime is compared to a field of the
        right table of an LEFT OUTER JOIN. Such comparisons are not supported by
         all database systems and are therefore not allowed.

  • Using ORDER BY for column that's not in SELECT statement of select list?

    Hi all.
    I have a select list on an APEX page at apex.oracle.com, and I would like to order this by the value of column UnitOrder.
    The SQL is as follows:
    SELECT DISTINCT foodunit.name AS display_value, foodunit.foodunitid AS return_value
    FROM foodunit, food
    WHERE foodunit.foodid = :P18_FOODID
    ORDER BY foodunit.unitorder ASC;Off course, this code won't work. And since it's a select list, I can't just add foodunit.unitorder to the SELECT statement. Also, I can't get rid of the DISTINCT, because then for some reason it tends to display an infinite amount of the same row...
    The point of ordering it by UnitOrder is that all units who begin with gram, ml, mg, kg,... etc, will be shown on top of the select list. All other food units will be shown on the second place and so on.
    The column UnitOrder holds either 1 or 2 as a value. 1 is the value for all rows that should be displayed at the top of the select list, 2 is the value for all the rest.
    So, what I want is that all rows in which the UnitOrder is 1, get displayed on top of the select list. Usually only 2 list items get shown in the select list at a time, depening on which food item a user has selected. The select list then refines to certain rows that match the foodid etc etc..
    If anyone has an idea, I'd be very happy to hear about it.

    Thanks! I didn't think about using a join. Code works now, and is as follows:
    SELECT foodunit.name AS display_value, foodunit.foodunitid AS return_value
    FROM foodunit
    INNER JOIN food
    ON food.foodid = foodunit.foodid 
    WHERE foodunit.foodid = :P18_FOODID
    ORDER BY foodunit.unitorder ASC;

  • Pass list of values in an array to the IN statement of SELECT in Oracle 10g

    Hi,
    This is what I have done so far...
    I have loaded the main array array_number_1 using BULK Collect. Within the loop I am filtering the data from this array and writing to another array array_number_2.
    I want to use the values from array_number_2 in the SELECT statement.
    Eg: SELECT sum(x_amount) charges
    FROM x_table
    WHERE id IN (array_number_2).
    Could you provide a solution to this preferrably with an example.
    thanks

    I'm not entirely following you, Visakh, but I have a SQL Task setup in which I have an expression that makes a call to a db2 database such as the abbreviated set example below.  The list of IDs in the IN statement must come from another  SQL Server
    database.   In the past I have  gotten the list of IDs, put them in a recordset and then put that in a for loop to iterate and make one call to db2 for each and every ID.   The single ID example can literally take days to run for 100,000 IDs.
     Therefore, I want to pull the entire set of results back at one time via a single (or at least fewer calls than there are IDs) DB2 call using 'in' instead.  Maybe I am overlooking something but I don't quite see how your example will get me where
    I want to go.  
    Set Example
    SELECT 
       A,
       B
    FROM 
        Table 1, 
        Table 2, 
    WHERE 
        Joins   
        AND PRSNEUP.ID in  ( This is where I want a list of IDs )
    Single ID Example
    SELECT     A,  
     B
    FROM   
      Table 1,      Table 2, 
    WHERE     
    Joins        AND PRSNEUP.ID =  ( VariableContainingASingleID

  • Prepared Statement, executing  SELECT TOP in Ms Access

    I'm having the following problem. I built an application fetching data without any problem from MS SQL Server, this was using prepared statements. Now i'm having this strange problem with the following query:
    SELECT TOP 1 *
    FROM table
    WHERE appliance_id = ?
    AND ttimestamp_initpk <= ?
    AND ((Type = ?) OR (Type = ?) OR (Type = ?) OR (Type = ?) OR (Type = ?) OR (Type = ?))
    ORDER BY ttimestamp_initpk DESC
    While on SQL Server this fetches just a record, on MS Access it fetches the whole set of records without worrying about TOP instruction.
    That is, it acts like a SELECT * FROM, and this slows down runtime behaviour.
    I'm using sun.jdbc.odbc.JdbcOdbcDriver, is it the problem?
    Thanks, Mirko

    Thanks for your answer, but i'm not sure this is the reason.
    I made one more test: i wrote a .Net application connecting to a MS Access using an ODBC connection. SELECT TOP statement is working fine, so i think i'll try another JDBC driver. Any other solution??
    Thanks,
    Mirko

  • QUESTION ON INSERT STATEMENT WITH SELECT

    Hi
    I have a table which contains three fields
    Table name : USERS
    ID NUMBER(10),
    NAME VARCHAR2(50),
    EMAIL VARCHAR2(50)
    SEQUENCE by name SEQ_ID
    I am trying to insert values into USERS from EMPLOYEE by virtue
    of insert into USERS (SELECT NAME, MAIL from EMPLOYEE) but i
    want to have one id for all the rows fetched from my inner
    query.
    I would like to know if here is a way, by which i can fetch a
    constant in my select statement which is not present in the
    table and use it like
    insert into USERS ( SELECT constant, NAME, MAIL FROM EMPLOYEE );
    where constant is some number unique for a given insertion.
    Thanks
    Arun

    Why not just try it? All you had to do was type
    insert into USERS SELECT 1, NAME, MAIL FROM EMPLOYEE ;
    and you would have had your answer immediately instead of
    waiting for me to tell you.
    rgds, APC

  • Update Statement using SELECT statement

    The following select query return 1 record to me
    [code]
    select  deptno , dname, empno , max_date, max(v_num)
      from (select  d.deptno , d.dname , e.empno ,max (ver_date)  over(partition by d.id ,d.no) max_date  ,v_num
                from  emp e ,dept d
              where  e.deptno=d.deptno and e.dname = d.dname and e.empno=1 and d.deptno =3 )
    group by  deptno , dname, empno , max_date  
    [/code]
    Now I need to update the above value to the emp table itself
    In emp table for the empno=1  I need to update the columns mx_Date and v_num columns with the above last 2 columns in the select statement (max_date, max(v_num) )
    How can I write the update statement for this.
    Thank You

    Something like this
    merge into emp e1
    using (
              select deptno
                   , dname
                   , empno
                   , max_date
                   , max(v_num) v_num
                from (
                       select d.deptno
                            , d.dname
                            , e.empno
                            , max (ver_date)  over(partition by d.id , d.no) max_date 
                            , v_num
                         from emp e
                            , dept d
                        where e.deptno = d.deptno
                          and e.dname  = d.dname
                          and e.empno  = 1
                          and d.deptno = 3
               group
                  by deptno
                   , dname
                   , empno
                   , max_date  
          ) e2
       on (
            e1.empno = e2.empno
    when matched then
        update set e1.mx_date = e2.max_date,
                   e1.v_num   = e2.v_num

  • Statement AUDIT SELECT TABLE also audits update, delete and inserts

    Hi,
    Database Oracle 11g.
    After turning on AUDIT with these 2 statements:
    SQL> ALTER SYSTEM SET audit_trail = "DB_EXTENDED" SCOPE=SPFILE;
    SQL> AUDIT SELECT TABLE BY ACCESS;
    then insert, update and delete statements are recorded in sys.aud$ as well as select statements.
    My expectation was to see only select statements in sys.aud$.
    Please clarify :-)
    Best regards
    Erik

    it should not record other action apart from select,can you crosscheck audit configuration by
    select * from DBA_OBJ_AUDIT_OPTS;
    SELECT * FROM ALL_DEF_AUDIT_OPTS;

Maybe you are looking for