How to optimized Multiple CASE statement

Hi..
Somebody please help me out to use most optimized Multiple CASE statement in below example.. 
Select
CAST(COUNT(DISTINCT(CASE WHEN period_id <350 THEN period_id END)) AS DECIMAL(30,0))  AS Column1,                  CAST(COUNT(DISTINCT(CASE WHEN period_id >=351 AND period_id<=375 THEN period_id END))
AS DECIMAL(30,0)) AS Column2,                                
CAST(COUNT(DISTINCT(CASE WHEN period_id >=376 AND period_id<=400 THEN period_id END)) AS DECIMAL(30,0)) AS Column3,                             
CAST(COUNT(DISTINCT(CASE WHEN period_id >=401 AND period_id<=450 THEN period_id END)) AS DECIMAL(30,0)) AS Column4,                             
CAST(COUNT(DISTINCT(CASE WHEN period_id >=451 AND period_id<=575 THEN period_id END)) AS DECIMAL(30,0)) AS Column5,
CAST(COUNT(DISTINCT(CASE WHEN pmc ='UVS' THEN pmc END)) AS DECIMAL(30,0)) AS Column6,                                
CAST(COUNT(DISTINCT(CASE WHEN pmc ='VAL' THEN pmc END)) AS DECIMAL(30,0)) AS Column7                            
FROM [Table1]
Thanks in Advance,
Deepak Goyal

How is an index going to help in a query with no where clause or join?
Rhetorical question but it brings to light the problem.  This query is going to produce a table/index scan precisely because there's no where clause.
You need to change the way you are thinking about the problem.  The problem isn't that you need a better performing case statement, the problem is that you need to minimize the number of records you ask SQL Server to read from disk.  You do that
by using a where clause or by joining to a smaller table.
Here's one option which should give you the desired results while performing much better:
create index idx_period_id on Table1 (period_id)
create index idx_pmc on Table1 (pmc) include (period_id)
select (select count(distinct period_id) from Table1 where period_id < 350) as Column1,
(select count(distinct period_id) from Table1 where period_id between 351 and 375) as Column2,
(select count(distinct period_id) from Table1 where period_id between 376 and 400) as Column3,
(select count(distinct period_id) from Table1 where period_id between 401 and 450) as Column4,
(select count(distinct period_id) from Table1 where period_id between 451 and 575) as Column5,
(select count(distinct period_id) from Table1 where pmc = 'UVS') as Column6,
(select count(distinct period_id) from Table1 where pmc = 'VAL') as Column7

Similar Messages

  • Help: How to include logic in multiple CASE statements.

    Hello Folks,
    I have this Query where am converting from Access to Oracle. Am little confused on how to write multiple CASE statements.Apprecitae your help.
        round(Sum(IIf(recovery_flg = 'NONCASH FEE RECEIVED',
                         IIf(feepaid < FEE, FEE - FEEPAID, FEE),
                         0)),
                 2)

    *(1) you can nest CASE* - CASE in a CASE
    CASE WHEN ecovery_flg = 'NONCASH FEE RECEIVED' THEN
         CASE WHEN feepaid < FEE THEN ....
         END
    ENDor
    *(2) you can try to rewrite it as one CASE*
    CASE WHEN ecovery_flg = 'NONCASH FEE RECEIVED' AND feepaid < FEE THEN...
         WHEN ecovery_flg = 'NONCASH FEE RECEIVED' AND feepaid >= FEE THEN ...
    END

  • Help with multiple case statements

    Hello,
    I am new to BO.  I am on XI 3.0.  SQL 2005.  In Designer, I am trying to create a measure in a financial universe that would end up being multiple case statements within one select.  This is what I tried to do, but it doesn't work with the two case statements.  Can I use an ELSE leading into the second CASE WHEN somehow?  How can I accomplish this?  Sorry for my ignorance!
    CASE WHEN dbo.ClientBudgetYear.DateStage1Approved > 01/01/1900 AND dbo.ClientBudgetMonth.Month = 12 THEN dbo.ClientBudgetMonth.Stage1Sales END
    CASE WHEN  dbo.ClientBudgetYear.DateStage1Approved > 01/01/1900 AND dbo.ClientBudgetMonth.Month = 11 THEN dbo.ClientBudgetMonth.Stage1Sales END
    Any Suggestions?
    Thanks,
    Holly

    Holly,
    I don't know enough about your data or requirement to provide a solution, however, the construct that you post will not work because it causes you to build an object with multiple case statements when only one case statement per object is permitted.  From what I see in your code I would be inclined to combine the two statements into one as such:
    CASE WHEN dbo.ClientBudgetYear.DateStage1Approved > 01/01/1900 AND dbo.ClientBudgetMonth.Month in (11,12) THEN dbo.ClientBudgetMonth.Stage1Sales else null END
    Thanks,
    John

  • How to write a case statement for the totals column of two different years (2013 and 2014) of the same month so that I can get a +/- column

    Please Help!!!
    How to write a case statement for the totals column of two different years (2013 and 2014) of the same month so that I can get a +/- column.
                                      January 2014         January
    2013                            +/-
                    Region   Entry   Exit  Total    Entry   Exit   Total   (Total of Jan2014-Total of Jan2013)
                    A               2         3      
    40        5       7        30                    40-30= 10

    What is a table structure? Sorry cannot test it right now..
    SELECT <columns>,(SELECT Total FROM tbl WHERE Y=2014)-(SELECT Total FROM tbl WHERE Y=2013)
    FROM tbl
    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 send multiple customer statements by email using RFKORD11 program.

    Hi All,
    How to send multiple customer statements by email using RFKORD11 program. Is it possible?
    As of now we copied the stanadard program and sending the customer statements by email, one by one.
    if i execute the z program it will show the customer statement and send mail option.
    if i click send mail it will send that customer statement to the corresponding customer.
    then again i need to click back, it will show next customer statement and click on send mail.
    Pl guide me, if any one worked on this program.
    thanks in advance.
    Regards,
    Mahesh

    Try execute the program in the background to see if that helps.

  • How to send multiple customer statements by email using RFKORD11

    Hi All,
    How to send multiple customer statements by email using RFKORD11 program.
    As of now we copied the stanadard program and sending the customer statements by email, one by one.
    if  i execute the z program it will show the customer statement and send mail option.
    if i click send mail it will send that customer statement to the corresponding customer.
    then again i need to click back, it will show next customer statement and click on send mail.
    Pl guide me, if any one worked on this program.
    Regards,
    Mahesh

    Hi .
    You first need to copy that program to Z and make the changes in it. Can you convert sapscript to smartform?
    then you can write a logic to send mail in the loop.
    to send the pdf file
    https://www.sdn.sap.com/irj/scn/wiki?path=/display/snippets/mailsendthroughoutputcontrols
    Regards,
    Madhuri
    Edited by: madhuri sonawane on Jun 10, 2009 4:20 PM

  • How to create nested CASE statements in PL/SQL

    Can anyone please tell how to create Nested CASE statements in PL/SQL with proper syntax?
    It would be better if you can help with an example.
    Thank you!

    Something like this:
    SQL> set serveroutput on
    SQL> declare
      2    v1 number := 2;
      3    v2 varchar2(1) := 'C';
      4  begin
      5    case v1
      6      when 1 then dbms_output.put_line('First');
      7      when 2 then begin
      8                    case v2
      9                      when 'A' then dbms_output.put_line('Found A');
    10                      when 'B' then dbms_output.put_line('Found B');
    11                      when 'C' then dbms_output.put_line('Found C');
    12                      else dbms_output.put_line('NONE');
    13                    end case;
    14                  end;
    15      else dbms_output.put_line('Else');
    16    end case;
    17  end;
    18  /
    Found C
    PL/SQL procedure successfully completed
    SQL> If you have further doubts regarding syntax you can read the docs on the Case statement here:
    http://download.oracle.com/docs/cd/E11882_01/appdev.112/e10472/case_statement.htm

  • How to execute multiple sql statements

    hi all
    i am wondering if i can execute multiple sql statements in one shot with >> execute immediate command
    for example:
    i define the variable as X := sql statement
    Y := sql statement
    z := sql statement
    can i do execute immediate (X,Y, Z);
    if yes how ?? and if not any possible alternate
    thanks

    Starting with Ganesh's code
    DECLARE
       l_statement                 VARCHAR2 (2000);
       v_passwd                    VARCHAR2 (200);
       v_username                  VARCHAR2 (200) := 'test';
       v_pwd_key                   VARCHAR2 (200) := 'lwty23';
       v_dblink_name               VARCHAR2 (2000);
       v_dblink_drop               VARCHAR2 (2000);
       v_dblink_create             VARCHAR2 (2000);
       v_dblink_check_connection   VARCHAR2 (2000);
       l_number                    NUMBER;
    BEGIN
       --<<c_instance>>
       FOR c_instance IN (SELECT *
                            FROM v_oracle_instances
                           WHERE environment = 'Developement')
       LOOP
          SELECT encpwd_owner.display_db_encpwd (v_username,
                                                 c_instance.host_name,
                                                 c_instance.instance_name,
                                                 v_pwd_key)
            INTO v_passwd
            FROM DUAL;
          v_dblink_name := c_instance.host_name || '_' || c_instance.instance_name;
          v_dblink_create :=
                ' CREATE DATABASE LINK '
             || v_dblink_name
             || ' CONNECT TO '
             || v_username
             || ' '
             || 'IDENTIFIED BY '
             || v_passwd
             || ' USING'
             || ' ''(DESCRIPTION=
    (ADDRESS=(PROTOCOL=TCP)(HOST= '
             || c_instance.host_name
             || ')(PORT='
             || c_instance.LISTENER_PORT
             || '))(CONNECT_DATA=(SID='
             || c_instance.instance_name
             || ')))''';
          v_dblink_check_connection := 'select 1 from global_name@' || v_dblink_name || '.QCM';    --- Notice this change. I am simply selecting 1. That should be enough to test the database link.
          v_dblink_drop := 'drop database link ' || v_dblink_name || '.QCMTLAF';
          -- l_statement := 'BEGIN ' || v_dblink_create ';' || v_dblink_check_connection ';' || v_dblink_drop '; END ;'
          BEGIN
              EXECUTE IMMEDIATE (v_dblink_create);
              DBMS_OUTPUT.PUT_LINE ('DB Link ' || v_dblink_name || ' Created');
         EXCEPTION
            WHEN others THEN
               dbms_output.put_line( 'Failed to create the database link ' || v_dblink_name  );
               dbms_output.put_line( dbms_utility.format_error_backtrace() );
               INSERT INTO error_table( column_list )
                 VALUES( <<list of values>> );
         END;
          EXECUTE IMMEDIATE (v_dblink_check_connection) INTO l_number;    --- Notice this.
          DBMS_OUTPUT.PUT_LINE ('DB Link ' || v_dblink_name || ' Tested');
          BEGIN
             EXECUTE IMMEDIATE (v_dblink_drop); 
             DBMS_OUTPUT.PUT_LINE ('DB Link ' || v_dblink_name || ' Dropped');
          EXCEPTION
             WHEN others THEN
               dbms_output.put_line( 'Failed to drop the database link ' || v_dblink_name  );
               dbms_output.put_line( dbms_utility.format_error_backtrace() );
               INSERT INTO error_table( column_list )
                 VALUES( <<list of values>> );
         END;
       END LOOP;
    END;But I agree with the point that others have brought up that it really doesn't make sense to create and drop a database link like this.
    Justin

  • How to use a case statement in where clause

    Hi All,
    I have a requirement which is to bring all the claims that are created in the last month.So, i wrote a query something like this
    select * from claims
    where
    (Month(ClaimOpenDate) = Month(Getdate())-1 and year(claimopendate) = year(getDate()))
    which would give me any new claims created in last month of current year, but this condition fails if we are in the first month of a new year( lets say if we are in 2016 jan then month(getdate())-1 would be 0 and year(getdate()) would be 2016 so we dont
    find any records where year is 2016 and month is 0 for claimopen).
    So, i would like to use a case statament or something which can help me get around this one.
    Can someone please help me with any suggestions?
    Thanks

    Hi Jason,
    Thanks a lot for your help. This is what exactly i am looking for but i just gave a sample query above below is my original query 
    select
    row_number() over (order by [ClaimNumber]) as DataElementName
    ,c.PolicyNumber as PolicyNum
    , c.FirstName as CustNameF
    ,c.LastName as CustNameL
    ,c.PolicyForm as PolType
    ,'Homesite' as Company
    ,[ClaimNumber] as ClaimNum
    ,E.office as Ofc
    ,e.Supervisior_FullName as Team
    , RIGHT(e.adjuster_Name ,LEN(e.adjuster_Name)- charindex(',' ,e.adjuster_Name)) as FORepF
    , case when charindex(',' ,e.adjuster_Name) <> 0 then left(e.adjuster_Name,charindex(',' ,e.adjuster_Name)-1) else e.adjuster_Name end as FORepL
    ,e.AdjusterID as RepC -- not sure
    ,CONVERT ( varchar,c.LossDate ,101) as DOL
    ,convert (varchar,c.ClaimOpenDate,101) as DOR
    ,rtrim(c.Loss_State) as LossSt
    ,c.Loss_ZipCode as LossZIP
    ,c.Loss_City as LossCity
    ,c.LossType as FOL
    ,'' as PR
    ,'' as PRNum
    ,1 as FeaNum
    ,'HO' as FeaType
    ,case when rtrim(c.claimStatus)= 'Closed' then 'Closed' else 'Open' end as FeaStat
    ,'' as FeaOpen
    ,'' as FeaClosed
    ,s.PaymentIndemnityAmount as PaidAmt
    ,s.ReserveIndemnityAmount as Reserve
    ,'' as Sub
    ,'' as Sal
    ,'' as FeatOwnOfc
    ,e.Supervisior_FullName as FeatOwnTeam
    ,RIGHT(e.adjuster_Name ,LEN(e.adjuster_Name)- charindex(',' ,e.adjuster_Name)) as FeatOwnRepF
    ,case when charindex(',' ,e.adjuster_Name) <> 0 then left(e.adjuster_Name,charindex(',' ,e.adjuster_Name)-1) else e.adjuster_Name end as FeatOwnRepL
    ,e.AdjusterID as FeatOwnRepCode
    ,NULL AS Description --not sure
    from [Stg].[HS_DW_RV_Claims] c
    inner join [dbo].[Claims_Primary_Adjuster] a on a.CLAIM_NUMBER = c.ClaimNumber
    inner join [dbo].[vw_Adjuster] e on e.adjuster_Name = a.primary_ADJUSTER
    left outer join [Stg].[HS_DW_LossClaimSummary] s on c.ClaimKey=s.ClaimKey
    where c.LoadSource = 'CMS'
    and
    (s.PaymentIndemnityAmount <>0 or s.PaymentExpenseAmount <>0)
    and
    ClaimOpenDate BETWEEN DATEADD(mm, DATEDIFF(mm, 0, CURRENT_TIMESTAMP) -1, 0) AND DATEADD(mm, DATEDIFF(mm, 0, CURRENT_TIMESTAMP), 0)
    UNION ALL
    select
    row_number() over (order by [ClaimNumber]) as DataElementName
    ,c.PolicyNumber as PolicyNum
    , c.FirstName as CustNameF
    ,c.LastName as CustNameL
    ,c.PolicyForm as PolType
    ,'Homesite' as Company
    ,[ClaimNumber] as ClaimNum
    ,E.office as Ofc
    ,e.Supervisior_FullName as Team
    , RIGHT(e.adjuster_Name ,LEN(e.adjuster_Name)- charindex(',' ,e.adjuster_Name)) as FORepF
    , case when charindex(',' ,e.adjuster_Name) <> 0 then left(e.adjuster_Name,charindex(',' ,e.adjuster_Name)-1) else e.adjuster_Name end as FORepL
    ,e.AdjusterID as RepC -- not sure
    ,CONVERT ( varchar,c.LossDate ,101) as DOL
    ,convert (varchar,c.ClaimOpenDate,101) as DOR
    ,rtrim(c.Loss_State) as LossSt
    ,c.Loss_ZipCode as LossZIP
    ,c.Loss_City as LossCity
    ,c.LossType as FOL
    ,'' as PR
    ,'' as PRNum
    ,1 as FeaNum
    ,'HO' as FeaType
    ,case when rtrim(c.claimStatus)= 'Closed' then 'Closed' else 'Open' end as FeaStat
    ,'' as FeaOpen
    ,'' as FeaClosed
    ,s.PaymentIndemnityAmount as PaidAmt
    ,s.ReserveIndemnityAmount as Reserve
    ,'' as Sub
    ,'' as Sal
    ,'' as FeatOwnOfc
    ,e.Supervisior_FullName as FeatOwnTeam
    ,RIGHT(e.adjuster_Name ,LEN(e.adjuster_Name)- charindex(',' ,e.adjuster_Name)) as FeatOwnRepF
    ,case when charindex(',' ,e.adjuster_Name) <> 0 then left(e.adjuster_Name,charindex(',' ,e.adjuster_Name)-1) else e.adjuster_Name end as FeatOwnRepL
    ,e.AdjusterID as FeatOwnRepCode
    ,DESCRIPTION --not sure
    from Stg.IG_Document D
    inner join [Stg].[HS_DW_RV_Claims] c on D.PARENTREF = C.ClaimNumber
    inner join [dbo].[Claims_Primary_Adjuster] a on a.CLAIM_NUMBER = c.ClaimNumber
    inner join [dbo].[vw_Adjuster] e on e.adjuster_Name = a.primary_ADJUSTER
    left outer join [Stg].[HS_DW_LossClaimSummary] s on c.ClaimKey=s.ClaimKey
    where c.LoadSource = 'CMS'
    and
    DESCRIPTION like '%Denial Letter%'
    and
    ClaimOpenDate BETWEEN DATEADD(mm, DATEDIFF(mm, 0, CURRENT_TIMESTAMP) -1, 0) AND DATEADD(mm, DATEDIFF(mm, 0, CURRENT_TIMESTAMP), 0)
    So if i use your logic in the end for both the where clauses its been more than 10 minutes and the query is still running however if i use my old method it doesnt even take a second. Looks like its affecting the execution plan. Any suggestions to get around
    this one please?
    Thanks

  • How to execute multiple SQL statements thru frontend?

    With SQL Server database, you can execute multiple SQL statements.
    Ex.
    SQLCommand cmd = new SQLCommand();
    cmd.CommandText = "SELECT * FROM EMP; SELECT * FROM DEPT";
    cmd.ExecuteXXX();
    Note that for SQL Server, ";" (semocolon) is used as a separator.
    What separator is required for Oracle ? Or rather, can I execute multiple SQL statements against Oracle database (10g) ?
    (Why I want to do it is a totally diff. subject !)
    Thanks,
    Ami.

    Hello,
    You could use an anonymous PL/SQL block to batch multiple statements.
    If you want to use SELECT statements, you would open a REF CURSOR for each SELECT and return the REF CURSOR to your application. INSERT, UPDATE, and DELETE statements can just be passed as is.
    A simple REF CURSOR example might look like:
    begin
      open :v_refcursor1 for select * from emp;
      open :v_refcursor2 for select * from dept;
    end;Where v_refcursor1 and v_refcursor2 are parameters defined as a REF CURSOR type.
    Hope that helps a bit...
    - Mark

  • How to execute multiple sql statements in oracle?

    I want to execute multiple statements in a single transaction in oracle. Following are my queries:
    Create table temp_table as Select * from table;
    SELECT * FROM temp_table d;
    drop table temp_table ;
    I am using sql comment text in asp.net
    I am using executenonquery command in asp.net.
    Thanks,
    Divya

    SigCle ,
    Here's an example that executes 3 statements;
    begin insert into foo values(1); insert into foo values(2); insert into foo values(3); end;
    923354,
    The block doesn't compile because temp_table doesn't exist at the point you're trying to compile the anonymous block. I'd recommend re-reading the doc link and forum link provided to get a better understanding of how temp tables work, as it's simply different with Oracle. You don't create Oracle temporary tables on the fly; you create them ahead of time and then just use them. The data itself is already specific to a particular session; you don't create and drop the table each time.
    Also, you can't just "select * from table" in plsql. The results have to GO SOMEWHERE. Usually you'd either open a cursor and process it in the block, or send out a ref cursor if you want to send the data to a client side app. The ref cursor data wouldn't actually be fetched until the block completes though, so you'd need to use ON COMMIT PRESERVE ROWS, which would also mean you'd need to clean up the data yourself (delete the data from the table when you're done with it).
    Corrections/comments welcome.
    Greg

  • How to execute multiple sql statement?

    In an single transaction I want to execute two update statements. I don't know how to break those statements and send to oracle from Asp.Net to execute.
    I tried go and ; .
    Below is myQuery string*
    update abc set One = 10 where Two = 3 ; update xyz set Three = 10 where Four = 3 ;
    Additional info
    I am using sql comment text in asp.net
    I am using executenonquery command in asp.net.

    Hi,
    If you want to execute multiple statements in a single transaction, you could either:
    a) create a local transaction (via an OracleTransaction object), then call executenonquery multiple times within that transaction, or
    b) pass them all in an anonymous block for a single round trip.. ie, begin update abc set One = 10 where Two = 3 ; update xyz set Three = 10 where Four = 3 ;end;
    The database doesn't permit multiple statements passed at once (other than in a plsql block).
    Hope it helps, corrections/comments welcome
    Greg
    PS, questions such as this would be better posted in the ODP.NET forum; this forum is for issues regarding ODT.NET (a VS plugin)
    ODP.NET

  • How to execute multiple sql statements in parallel ?

    Hi There,
    I have 10 stored procedures, each one will take approximately 5 seconds to run individually.
    Now I need to combine the results of these 10 stored procedures into single result set.
    So I have created one more stored procedure "proc_AllSPs" to get the single result set.
    The procedure "proc_AllSPs" is taking one minute to run because all the procedures inside the "proc_AllSPs" are running
    one after the other and taking 5 seconds each.
    If there is any other way that all the procedures run parallelly, then the procedure "proc_AllSPs" can run in 5 seconds time.
    Sorry if I am not being elaborated.
    PLease get back to me if any piece of information is needed.
    Any kind of help is truly thankful.
    Thanks,
    SequelBug

    Could you tell me how to execute two stored procedures or two sql statements in parallel
    For eg:
    First procedure name is proc_sp1 which takes 1 minute to run
    Second procedure name is proc_sp2 which takes 1 minute to run
    I want to accomplish the below query in 1 minute by executing statement1 and statement2 parallelly.
    go
    select * from openrowswt('sqloledb','server','exec proc_sp1')    --statement1
    union
    select * from openrowset('sqloledb','server','exec proc_sp2')     --statement2
    go
    OR
    go
    Select * into #Temp1  from openrowswt('sqloledb','server','exec proc_sp1') --statement1
    select * into #Temp2 from openrowset('sqloledb','server','exec proc_sp2') --statement2
    Select * from #Temp1
    UNION ALL
    Select * from #Temp2
    go
    Thanks,
    SequelBug

  • Multiple case statements with aggregates- SQL

    Hi guys
    Here is my ddl
    create table TestTable
      Bill_date                    DATE,
      Phone_no                     NUMBER(10),
      Planlvl1                     VARCHAR2(20),
      Planlvl2                     VARCHAR2(20)
      Revenue                      NUMBER                     
    INSERT INTO TestTable
    Values
    ('1/01/2014' , 64221, 'Bundle', 'SpecialPack1', '$23'),
    ('1/01/2014'' , 64221, 'Bundle', 'PlanA', '$32'),
    ('1/01/2014' , 65211, 'Bundle', 'SpecialPack2', '$3'),
    ('1/01/2014' , 65211, 'Bundle', 'SpecialPack1', '$23'),
    ('1/01/2014' , 66211, 'Bundle', 'PlanB', '$34'),
    ('1/01/2014' , 66211, 'Bundle', 'SpecialPack2', '$3'),
    ('1/01/2014' , 66222, 'Bundle', 'SpecialPack1', '$23'),
    ('1/01/2014' , 66222, 'Bundle', 'SpecialPack2', '$3'),
    ('1/01/2014' , 66222, 'Bundle', 'PlanB', '$65'),
    ('1/01/2014' , 32444, 'Non_bundle', 'Casual1', '$32'),
    ('1/01/2014' , 324441, 'Non_bundle', 'Casual2', '$76'),
    ('1/01/2014' , 65444, 'Non_bundle', 'Casual1', '$12'),
    ('1/01/2014' , 65444, 'Bundle', 'PlanB', '$98'),
    ('1/01/2014' , 54322, 'Bundle', 'PlanA', '$12'),
    ('1/01/2014' , 54322, 'Non_bundle', 'Casual', '$12')
    Expected Outcome:
    Bill_date PlanLvl2 PhonenoCount
    '01/01/2014' 'SpecialPack1' 1
    '01/01/2014' 'SpecialPack2' 3
    '01/01/2014' 'Casual1' 1
    '01/01/2014' 'Casual2' 1
    '01/01/2014' 'PlanA' 1
    '01/01/2014' 'PlanB' 1
    Basically I have to count all the phone nos grouped by plans in a certain way:
    If PlanLvl1 = Bundle, then I have to look  at planLvl2 and see if that phone no has ' SpecialPack%' ,and also another plan,them 'Special pack' gets the priority and the phone no gets counted in the special pack.
    In case when PlanLvl1 = Bundle and a phone no has both 'Special Packs' as their plans, then the phone no will be counted under the 'Special Pack' with higher Revenue.
    In case where PalnLvl is 'Bundle' and a phone no has multiple 'Special Packs' and a non special, that ph no will only be counted once under 'Special Pack; of higher rev as compared to the special pack of lower rev.
    Now there are also PlanLvl1 which are 'Non_Bundles' which means they do not have any 'SpecialPacks' but if a ph no with 'NonBundle' plan has 2 different plans under planLvl2, we need to count that ph no for eack planLvl2..
    Then there is a scenario where a ph no can have bundles as well as non bundles and in that case we just have to count that ph no in bundles and not in non-bundles.
    As I mentioned , 'SpecialPack2' will get a preference over special pack 1 if a phone no has got both of these
    Hope this helps

    I;m not sure exactly what your rules are since you specify both "In case when PlanLvl1 = Bundle and a phone no has both 'Special Packs' as their plans, then the phone no will be counted under the 'Special Pack' with higher Revenue" and "As I mentioned ,
    'SpecialPack2' will get a preference over special pack 1 if a phone no has got both of these".  I went with the rule "As I mentioned , 'SpecialPack2' will get a preference over special pack 1 if a phone no has got both of these" since that seemed to match
    the result you say you want.  I also changed the datatypes to valid SQL Server datatypes.
    create table TestTable
    Bill_date DATE,
    Phone_no Decimal(10,0),
    Planlvl1 VARCHAR(20),
    Planlvl2 VARCHAR(20),
    Revenue money
    INSERT INTO TestTable
    Values
    ('1/01/2014' , 64221, 'Bundle', 'SpecialPack1', '$23'),
    ('1/01/2014' , 64221, 'Bundle', 'PlanA', '$32'),
    ('1/01/2014' , 65211, 'Bundle', 'SpecialPack2', '$3'),
    ('1/01/2014' , 65211, 'Bundle', 'SpecialPack1', '$23'),
    ('1/01/2014' , 66211, 'Bundle', 'PlanB', '$34'),
    ('1/01/2014' , 66211, 'Bundle', 'SpecialPack2', '$3'),
    ('1/01/2014' , 66222, 'Bundle', 'SpecialPack1', '$23'),
    ('1/01/2014' , 66222, 'Bundle', 'SpecialPack2', '$3'),
    ('1/01/2014' , 66222, 'Bundle', 'PlanB', '$65'),
    ('1/01/2014' , 32444, 'Non_bundle', 'Casual1', '$32'),
    ('1/01/2014' , 324441, 'Non_bundle', 'Casual2', '$76'),
    ('1/01/2014' , 65444, 'Non_bundle', 'Casual1', '$12'),
    ('1/01/2014' , 65444, 'Bundle', 'PlanB', '$98'),
    ('1/01/2014' , 54322, 'Bundle', 'PlanA', '$12'),
    ('1/01/2014' , 54322, 'Non_bundle', 'Casual', '$12')
    ;With cte As
    (Select Bill_date, Phone_no, Planlvl1, Planlvl2, Revenue,
    Row_Number() Over (Partition By Bill_Date, Phone_no Order By
    Case When Planlvl1 = 'Bundle' And Planlvl2 Like 'SpecialPack2' Then 0 Else 1 End,
    Case When Planlvl1 = 'Bundle' And Planlvl2 Like 'SpecialPack1' Then 0 Else 1 End,
    Case When Planlvl1 = 'Bundle' Then Revenue Else -1 End Desc) As rn,
    Min(Case When Planlvl1 = 'Bundle' Then 0 Else 1 End) Over(Partition By Bill_Date, Phone_no) As NumberHasOnlyNonBundle
    From TestTable)
    Select Bill_date, Planlvl2, COUNT(*) As PhoneNoCount
    From cte
    Where rn = 1 Or NumberHasOnlyNonBundle = 1
    Group By Bill_date, Planlvl2;
    Tom

  • How to add multiple skin states to SkinnableContainerSkin so that can switch among states

    Hi All,
    I have a xml which represents 2 views of SkinnableContainer, xml being parsed and converted to ui elements and stored into 2 array variables based on display property of the tag
    initially adding 1 set of array element to Container
    whenever a button clicked to show different set of array elements, calling removeAllElements() and adding different set of elements from 2nd array
    Can somebody help me converting this application to utilize "Skin States"  feature
    Sorry, Could not find way to attach demo project, copied code bellow
    Thanks in advance...
    /src/ContainerDemo.mxml
         /com.containerdemo.controls
              ButtonControl.as
              ContainerControl.mxml
              CustomContainer.as
              CustomControls.mxml
              IControl.as
              ParentControl.mxml
         /com.containerdemo.skins
              ButtonControlSkin.mxml
              CustomContainerSkin.mxml
         /com.containerdemo.utils
              XmlUtil.as
    ContainerDemo.mxml
    <?xml version="1.0" encoding="utf-8"?>
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
                                     xmlns:s="library://ns.adobe.com/flex/spark"
                                     xmlns:mx="library://ns.adobe.com/flex/mx"
                                     minWidth="700" minHeight="500"
                                     xmlns:controls="com.containerdemo.controls.*">
              <s:VGroup paddingBottom="20" paddingLeft="20"
                                    paddingRight="20" paddingTop="20" gap="20"
                                    horizontalCenter="0">
                        <s:Label text="Flex states demo" fontSize="30"/>
                        <controls:ParentControl id="pc" />
              </s:VGroup>
    </s:Application>
    XmlUtil.as
    package com.containerdemo.utils {
              import com.containerdemo.controls.ButtonControl;
              import com.containerdemo.controls.ContainerControl;
              import com.containerdemo.controls.CustomContainer;
              import com.containerdemo.controls.IControl;
              public class XmlUtil {
                        public static var ELEMENTS:Object = {
                                  "buttonElement": ButtonControl,
                                  "containerElement": ContainerControl
                        public static function parse(xml:XML):IControl {
                                  var name:String = xml.name();
                                  var clazz:Class = ELEMENTS[name];  
                                  var elem:IControl = new clazz();
                                  elem.parse(xml);
                                  return elem;
    CustomContainerSkin.mxml
    <?xml version="1.0" encoding="utf-8"?>
    <s:SparkSkin xmlns:fx="http://ns.adobe.com/mxml/2009"
                                   xmlns:s="library://ns.adobe.com/flex/spark"                               
                                   xmlns:mx="library://ns.adobe.com/flex/mx">
              <fx:Metadata>
                        [HostComponent("com.containerdemo.controls.CustomContainer")]
              </fx:Metadata>
        <s:states>
            <s:State name="normal" />
            <s:State name="disabled" />
        </s:states>
              <s:Group id="rectGroup">
                        <s:Rect left="0" right="0" top="0" bottom="0" radiusX="8" radiusY="8">
                                  <s:stroke>
                                            <s:SolidColorStroke weight="2" color="#FF0000" alpha="0.8" />
                                  </s:stroke>
                        </s:Rect>
                        <s:HGroup top="10" left="10" right="10" gap="4">
                                  <s:Label id="containerLabel" text="{this.hostComponent.label}" />
                                  <s:Button id="compOrExpButton" label="{this.hostComponent.btnLabel}" />
                                  <mx:Spacer width="100%" />
                        </s:HGroup>
                        <s:Group id="contentGroup" left="16" right="16" top="32" bottom="32" />
              </s:Group>
    </s:SparkSkin>
    ButtonControlSkin.mxml
    <?xml version="1.0" encoding="utf-8"?>
    <s:SparkSkin xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark"
                 xmlns:fb="http://ns.adobe.com/flashbuilder/2009"
                                   minWidth="21" minHeight="21" alpha.disabled="0.5">
              <fx:Metadata>
                        [HostComponent("com.containerdemo.controls.ButtonControl")]
              </fx:Metadata>
        <s:states>
            <s:State name="up" />
            <s:State name="over" />
            <s:State name="down" />
            <s:State name="disabled" />
        </s:states>
              <s:Label id="labelDisplay"
                 textAlign="center"
                 verticalAlign="middle"
                 maxDisplayedLines="1" minWidth="20"
                 horizontalCenter="0" verticalCenter="1"
                 left="10" right="10" top="2" bottom="2">
        </s:Label>
    </s:SparkSkin>
    ParentControl.mxml
    <?xml version="1.0" encoding="utf-8"?>
    <s:Group xmlns:fx="http://ns.adobe.com/mxml/2009"
                         xmlns:s="library://ns.adobe.com/flex/spark"
                         xmlns:mx="library://ns.adobe.com/flex/mx"
                         xmlns:controls="com.containerdemo.controls.*"
                         creationComplete="group1_creationCompleteHandler(event)">
              <fx:Declarations>
                        <fx:XML id="compXml" xmlns="">
                                  <elems>
                                            <buttonElement id="b1" label="Element1" />
                                            <containerElement id="c2" label="Container2" display="comp">
                                                      <comp>
                                                                <buttonElement id="c2b1" label="Element5 (Comp)" />
                                                                <buttonElement id="c2b2" label="Element6 (Comp)" />
                                                                <containerElement id="c2c1" label="Container c2c1" display="comp">
                                                                          <comp>
                                                                                    <buttonElement id="c2c1b1" label="Element c2c1b1 (Comp)" />
                                                                                    <buttonElement id="c2c1b2" label="Element c2c1b2 (Comp)" />
                                                                          </comp>
                                                                </containerElement>
                                                                <containerElement id="c2c2" label="Container c2c2" display="comp">
                                                                          <comp>
                                                                                    <buttonElement id="c2c2b1" label="Element c2c2b1 (Comp)" />
                                                                                    <buttonElement id="c2c2b2" label="Element c2c2b2 (Comp)" />
                                                                          </comp>
                                                                </containerElement>
                                                      </comp>
                                            </containerElement>
                                            <buttonElement id="b3" label="Element7" />
                                  </elems>
                        </fx:XML>
                        <fx:XML id="expXml" xmlns="">
                                  <elems>
                                            <buttonElement id="b1" label="Element1" />
                                            <containerElement id="c2" label="Container2" display="exp">
                                                      <comp>
                                                                <buttonElement id="c2b2" label="Element5 (Comp)" />
                                                                <buttonElement id="c2b2" label="Element6 (Comp)" />
                                                                <containerElement id="c2c1" label="Container c2c1" display="exp">
                                                                          <comp>
                                                                                    <buttonElement id="c2c1b1" label="Element c2c1b1 (Comp)" />
                                                                                    <buttonElement id="c2c1b2" label="Element c2c1b2 (Comp)" />
                                                                          </comp>
                                                                          <exp>
                                                                                    <buttonElement id="c2c1b3" label="Element c2c1b3 (Exp)" />
                                                                                    <buttonElement id="c2c1b4" label="Element c2c1b4 (Exp)" />
                                                                          </exp>
                                                                </containerElement>
                                                                <containerElement id="c2c2" label="Container c2c2" display="comp">
                                                                          <comp>
                                                                                    <buttonElement id="c2c2b1" label="Element c2c2b1 (Comp)" />
                                                                                    <buttonElement id="c2c2b2" label="Element c2c2b2 (Comp)" />
                                                                          </comp>
                                                                          <exp>
                                                                                    <buttonElement id="c2c2b3" label="Element c2c2b3 (Exp)" />
                                                                                    <buttonElement id="c2c2b4" label="Element c2c2b4 (Exp)" />
                                                                          </exp>
                                                                </containerElement>
                                                      </comp>
                                                      <exp>
                                                                <containerElement id="c4" label="Container4" display="comp">
                                                                          <comp>
                                                                                    <buttonElement id="c4b1" label="Element 555(Comp)" />
                                                                                    <buttonElement id="c4b2" label="Element 655 (Comp)" />
                                                                          </comp>
                                                                          <exp>
                                                                                    <buttonElement id="c4b3" label="Element 335 (Exp)" />
                                                                                    <buttonElement id="c4b4" label="Element 126 (Exp)" />
                                                                          </exp>
                                                                </containerElement>
                                                      </exp>
                                            </containerElement>
                                            <buttonElement id="b3" label="Element7" />
                                  </elems>
                        </fx:XML>
              </fx:Declarations>
              <fx:Script>
                        <![CDATA[
                                  import mx.events.FlexEvent;
                                  protected function group1_creationCompleteHandler(event:FlexEvent):void {
                                            this.customControls.parse(compXml);
                        ]]>
              </fx:Script>
              <controls:CustomControls id="customControls" />
    </s:Group>
    IControl.as
    package com.containerdemo.controls
              import mx.core.IVisualElement;
              public interface IControl extends IVisualElement {
                        function parse(xml:XML):void;
    CustomControls.mxml
    <?xml version="1.0" encoding="utf-8"?>
    <s:Group xmlns:fx="http://ns.adobe.com/mxml/2009"
                         xmlns:s="library://ns.adobe.com/flex/spark"
                         xmlns:mx="library://ns.adobe.com/flex/mx"
                         implements="com.containerdemo.controls.IControl">
              <fx:Script>
                        <![CDATA[
                                  import com.containerdemo.utils.XmlUtil;
                                  public function parse(xml:XML):void {
                                            for each (var child:XML in xml.children()) {
                                                      var e:IControl = XmlUtil.parse(child);
                                                      this.addElement(e);
                        ]]>
              </fx:Script>
              <s:layout>
                        <s:HorizontalLayout verticalAlign="middle" gap="15"
                                                                          paddingLeft="16" paddingRight="16"
                                                                          paddingTop="16" paddingBottom="16" />
              </s:layout>
    </s:Group>
    CustomContainer.as
    package com.containerdemo.controls
              import com.containerdemo.skins.CustomContainerSkin;
              import com.containerdemo.utils.XmlUtil;
              import flash.events.MouseEvent;
              import mx.collections.ArrayCollection;
              import spark.components.Button;
              import spark.components.Group;
              import spark.components.SkinnableContainer;
              public class CustomContainer extends SkinnableContainer implements IControl {
                        [SkinPart(required="true")]
                        public var compOrExpButton:Button;
                        [SkinPart(required="true")]
                        public var rectGroup:Group;
                        private var dispState:String;
                        private var _label:String;
                        private var _cid:String;
                        private var compControls:ArrayCollection;
                        private var expControls:ArrayCollection;
                        public function CustomContainer() {
                                  this.setStyle("skinClass", Class(CustomContainerSkin));
                        public function parse(xml:XML):void {
                                  this.compControls = null;
                                  this.expControls = null;
                                  compControls = new ArrayCollection;
                                  expControls = new ArrayCollection;
                                  this.dispState = xml.@display;
                                  this.label = xml.@label;
                                  this.cid = xml.@id;
                                  for each (var child:XML in xml.comp.children()) {
                                            var e:IControl = XmlUtil.parse(child);
                                            this.compControls.addItem(e);
                                            //trace((e is ButtonControl).label);
                                  for each (var child1:XML in xml.exp.children()) {
                                            var e1:IControl = XmlUtil.parse(child1);
                                            this.expControls.addItem(e1);
                                            //trace((e1 as ButtonControl).label);
                                  showControls();
                        [Bindable]
                        public function set cid(value:String):void {
                                  this._cid = value;
                        public function get cid():String {
                                  return this._cid;
                        public function showControls():void {
                                  if (this.dispState == "comp") {
                                            showCompControls();
                                  } else {
                                            showExpControls();
                        public function showCompControls():void {
                                  if (this.numElements >0)
                                            this.removeAllElements();
                                  for each (var e:IControl in compControls) {
                                            this.addElement(e);
                                  this.btnLabel = "Exp";
                                  this.invalidateSkinState();
                        public function showExpControls():void {
                                  if (this.numElements >0)
                                            this.removeAllElements();
                                  for each (var e:IControl in expControls) {
                                            this.addElement(e);
                                  this.btnLabel = "Comp";
                                  this.invalidateSkinState();
                        public function get ownerContainer():CustomContainer {
                                  return this.owner as CustomContainer;
                        public var b:Boolean = true;
                        public function displayCompOrExpControls(event:MouseEvent):void {
                                  if (this.btnLabel == "Exp") {
                                            if (b) {
                                                      this.reParse();
                                                      b = false;
                                            } else {
                                                      this.showExpControls();
                                  } else {
                                            this.showCompControls();
                        public function reParse():void {
                                  /*if (this.owner && (this.owner is CustomContainer))
                                            (this.owner as CustomContainer).reParse();
                                  else {*/
                                            var xml:XML = this.parentApplication.pc.expXml;
                                            var expXml:XMLList = xml.descendants().(attribute("id") == this.cid);
                                            this.parse(expXml[0]);
                        private var _btnLabel:String;
                        public function get btnLabel():String {
                                  return this._btnLabel;
                        [Bindable]
                        public function set btnLabel(value:String):void {
                                  this._btnLabel = value;
                        public function get label():String {
                                  return this._label;
                        [Bindable]
                        public function set label(value:String):void {
                                  this._label = value;
                        override protected function partAdded(partName:String, instance:Object):void {
                                  super.partAdded(partName, instance);
                                  if (instance == this.compOrExpButton)
                                            this.compOrExpButton.addEventListener(MouseEvent.CLICK, displayCompOrExpControls, false, 0, true);
                        override protected function partRemoved(partName:String, instance:Object):void {
                                  super.partRemoved(partName, instance);
                                  if (instance == compOrExpButton)
                                            this.compOrExpButton.removeEventListener(MouseEvent.CLICK, displayCompOrExpControls, false);
    ContainerControl.mxml
    <?xml version="1.0" encoding="utf-8"?>
    <controls:CustomContainer xmlns:fx="http://ns.adobe.com/mxml/2009"
                                                                  xmlns:s="library://ns.adobe.com/flex/spark"
                                                                  xmlns:mx="library://ns.adobe.com/flex/mx"                                                              
                                                                  xmlns:controls="com.containerdemo.controls.*">
              <controls:layout>
                        <s:HorizontalLayout gap="20"
                                                                          paddingLeft="16" paddingRight="16"
                                                                          paddingBottom="16" paddingTop="16" />
              </controls:layout>
    </controls:CustomContainer>
    ButtonControl.as
    package com.containerdemo.controls
              import com.containerdemo.skins.ButtonControlSkin;
              import spark.components.Button;
              public class ButtonControl extends Button implements IControl {
                        public function ButtonControl() {
                                  this.setStyle("skinClass", Class(ButtonControlSkin));
                        public function parse(xml:XML):void {
                                  this.label = xml.@label;

    Could somebody help me?

Maybe you are looking for

  • Page numbers in PDF?

    I cannot figure out how to identify the page numbers of a PDF document when I view it in Safari 5.0.3. The original paper document has its own numbering system, but the PDF page-numbers are completely different. When I go to print individual pages of

  • In Windows 7, my iTunes shuts down when I try to verify my account. Can anyone help? Thanks!

    I downloaded and installed the new iTunes 12 on my Windows 7 computer. Playing songs in iTunes work but when I login to my account. It says that it needs to be verified. iTunes closes before I can go through the verification process. Thanks for any h

  • Performance Problem After Upgrade

    Hi Gurus, We have successfully Upgrade our system R3 4.6c to ECC6, Database Oracle 10g on AIX. Now we are facing Performance Problem. when we are checking Tables are taking Huge time to update data. Regards, Darshan...

  • IllegalStateException whit Frames using JSP

    Hi friends! I have a huge problem. I have 2 servlets and 2 JSPs, my first servlet (QueryServlet) forward normally. but in the second Servlet (PersDataServlet) not. appears an Exception like this: IllegalStateException: Cannot forward after response h

  • Casdade LOV with conditional display

    Hi -- I have 2 prompts - the second prompt is constrained by the first so when I select Southeast region in prompt one, it only gives me the States in that region within the second prompt. I am hoping to only show the second prompt after the first on