Filter by Sum without Grouping

i have a resultset that i generate from a query that Looks like this:
  Select Employee, Month,
(select case
when Status = '---'
then 0 Else
1 end) as PlaningValue     
  From   PlanningTable PT
  Where  Month >=
@From Month and Month
<= @ToMonth
The Result of this Looks something like this:
|Employee| Month   
| PlaningValue |
|George    |2014-01 
|                
1 |
|George    |
2014-02 |                
1 |
|George    |
2014-03 |                 0
|
|Andrew    |
2014-01 |               
0 |
|Andrew    |
2014-02 |               
1 |
|Andrew    |
2014-03 |               
0 |
|Howard    |
2014-01 |               
1 |
|Howard    |
2014-02 |               
1 |
|Howard    |
2014-03 |                1
|
Now what i want is the following:
Filter out Employee's who, over the three month period, have a total planing Value of 3, in the example above, Howard would be filtered out.
Is there a way to do this nicely or is it all just impossible to even thin ?
(Remark: Since i am going to use the Query on Reporting Services, i can't use the OVER function)
Thank you all for your help

Jingyang's answer is a top choice, assuming SQL Server 2005 or greater (you didn't say what version, everybody should!).  I wrote up a version doing the same thing before I noticed Jinyang's answer already was here.  The last item in the list is
a derived query version, same net effect as using the WITH statement.
Create_Demo_table:
Declare @Demo Table (employee varchar(99), month varchar(77), status int)
Insert @Demo
Select 'George', '2014-01 ', 1
UNION ALL Select 'George', '2014-02', 1
UNION ALL Select 'George', '2014-03', 0
UNION ALL Select 'Andrew', '2014-01', 0
UNION ALL Select 'Andrew', '2014-02', 1
UNION ALL Select 'Andrew', '2014-03', 0
UNION ALL Select 'Howard', '2014-01', 1
UNION ALL Select 'Howard', '2014-02', 1
UNION ALL Select 'Howard', '2014-03', 1
With_Stmt:
;With X as
Select *
, sum(status) over(partition by employee) as sumStat
from @Demo
where month between '2014-01' and '2014-03'
Select * from X where SumStat < 3
Derived_query:
Select * from
Select *
, sum(status) over(partition by employee) as sumStat
from @Demo
where month between '2014-01' and '2014-03'
) Derived1
where Sumstat < 3

Similar Messages

  • SUM WITHOUT GROUP CLAUSE

    I want to sum the total of Positive Balances and Negative Balances in table. My DDL is as under:-
    CREATE TABLE LUQMAN
    (ID NUMBER(1),
    AMOUNT NUMBER(5));
    INSERT INTO LUQMAN VALUES(1,20000);
    INSERT INTO LUQMAN VALUES(1,-2000);
    INSERT INTO LUQMAN VALUES(1,5000);
    INSERT INTO LUQMAN VALUES(1,20000);
    INSERT INTO LUQMAN VALUES(1,2300);
    INSERT INTO LUQMAN VALUES(2,-50000);
    INSERT INTO LUQMAN VALUES(2,-2000);
    INSERT INTO LUQMAN VALUES(2,5000);
    INSERT INTO LUQMAN VALUES(2,20000);
    INSERT INTO LUQMAN VALUES(2,2300);
    INSERT INTO LUQMAN VALUES(3,20000);
    INSERT INTO LUQMAN VALUES(3,-2000);
    INSERT INTO LUQMAN VALUES(3,5000);
    INSERT INTO LUQMAN VALUES(3,20000);
    INSERT INTO LUQMAN VALUES(3,2300);
    INSERT INTO LUQMAN VALUES(4,-50000);
    INSERT INTO LUQMAN VALUES(4,-2000);
    INSERT INTO LUQMAN VALUES(4,5000);
    INSERT INTO LUQMAN VALUES(4,20000);
    INSERT INTO LUQMAN VALUES(4,2300);
    COMMIT;
    The query should return One Row Answer as under:-
    POSITIVE NEGATIVE
    90600 -47100
    I tried following but could not got the correct answer.
    SELECT CASE WHEN ID IN (1,2,3,4)
    AND SUM(AMOUNT)>0 THEN SUM(AMOUNT) ELSE 0 END POSITIVE,
    CASE WHEN ID IN (1,2,3,4)
    AND SUM(AMOUNT)<0 THEN SUM(AMOUNT) ELSE 0 END NEGATIVE
    FROM LUQMAN;
    Any Idea please, how to return above One Single Row ? I want one cumulative balance, not by ID Group.
    Thanks and Regards,
    Luqman

    SQL> ed
    Wrote file afiedt.buf
      1  select sum(positive),sum(negative) from
      2  (
      3  select case when sign(amount)=1 then amount end positive,
      4  case when sign(amount)=-1 then amount end negative from LUQMAN
      5* )
    SQL> /
    SUM(POSITIVE) SUM(NEGATIVE)
           149200       -108000
    SQL> SELECT * FROM LUQMAN
      2  /
            ID     AMOUNT
             1      20000
             1      -2000
             1       5000
             1      20000
             1       2300
             2     -50000
             2      -2000
             2       5000
             2      20000
             2       2300
             3      20000
            ID     AMOUNT
             3      -2000
             3       5000
             3      20000
             3       2300
             4     -50000
             4      -2000
             4       5000
             4      20000
             4       2300
    20 rows selected.
    luqman123 wrote:Hi,
    Your query returning wrong total.Can you check your inserts again ...
    HTH

  • SUM without Group by

    Hi,
    I have a table like this..
    Type      Amount      ID      Num      ActId
    Primary 256.32      12345      01      7899
    None     125.21      12345      01      7900
    None     456.87      12345      01      7901
    Primary 1258.45     98745      04      7902
    Primary 468.11      45565      06      7903
    None     1258.45     45565      06      7904
    None      200.00      85598      09      7905I want to sum Amounts based on ID and Type. I DON'T want to use GROUP BY.. I want SUM (Amount) OVER (PARTITION BY ..
    Result:
    Type      Amount      ID      Num
    Primary 838.4      12345      01           -- Sum of First 3 rows
    Primary 1258.45     98745      04 -- display 4th row directly becuase its primary
    Primary 1726.56     45565      06           -- Sum of 5th and 6th rowsthanks

    Not sure why you don't want to use group by, but...
    SQL> WITH t AS (SELECT 'Primary' type, 256.32 amount, 12345 id, '01' num, 7899 actid FROM dual UNION ALL
      2             SELECT 'None', 125.21, 12345, '01', 7900 FROM dual UNION ALL
      3             SELECT 'None', 456.87, 12345, '01', 7901 FROM dual UNION ALL
      4             SELECT 'Primary', 1258.45, 98745, '04', 7902 FROM dual UNION ALL
      5             SELECT 'Primary', 468.11, 45565, '06', 7903 FROM dual UNION ALL
      6             SELECT 'None', 1258.45, 45565, '06', 7904 FROM dual UNION ALL
      7             SELECT 'None', 200.00, 85598,'09', 7905 FROM dual)
      8  SELECT type, amount, id, num
      9  FROM (SELECT type, id, num,
    10               SUM(amount) OVER (PARTITION BY id) amount
    11        FROM t)
    12  WHERE type = 'Primary'
    13  ORDER BY num;
    TYPE        AMOUNT         ID NU
    Primary      838.4      12345 01
    Primary    1258.45      98745 04
    Primary    1726.56      45565 06John

  • Sum Current Group With filter

    Dear All,
    I have problem to sum data using filter/conditon
    i want to sum data like this:
    No Budget SM GG
    1.2 *400 200*
    1.2.1 100 100
    1.2.2 200 200
    1.2.3 300 300
    1.3 400 400
    and using
    <?sum(current-group()/TotalPrice[.!='' and PaymentAllocation='GG'])?>
    but show no data
    i also tried
    <?xdoxslt:set_variable($_XDOCTX, ’INITGG’, xdoxslt:get_variable($_XDOCTX, ’INITGG’)
    +xdoxslt:ifelse(PaymentAllocation='GG',xdoxslt:ifelse(TotalPrice[.!=''],TotalPrice,0),0))?>
    but nothing happen, seem the code didn't recognized the group(have 2 group inside)
    Please help me
    Thank so much
    Regards
    Cecilia

    You can use <?sum(current-group()/TotalPrice[.!='' and ../PaymentAllocation='GG'])?>

  • Nested Group Function without Group By Problem

    Hey everyone,
    I have 3 tables as below:
    TABLES
    ITEM (Item_no, Item_price, desc)
    DeliveryItem (delivery_no, item_no, quantity)
    Delivery (delivery_no, delivery_date)
    SELECT desc, MAX(SUM(quantity)) FROM DeliveryItem, Item, Delivery WHERE Item.item_no = DeliveryItem.item_no AND Delivery.delivery_no = deliveryitem.delivery_no;
    And I'm trying to output description of most delivered item but I got an error like SQL Error: ORA-00978: nested group function without GROUP BY. Could you help me to fix my code?
    Thanx

    Hi,
    DESC is not a good column name; you could get errors if the parser thinks it means DESCending. I used DESCRIPTION instead, below.
    I think the best way is to do the SUM in a sub-query, lkike this:
    WITH     got_r_num     AS
         SELECT       item_no
         ,       SUM (quantity)     AS total_quantity
         ,       RANK () OVER (ORDER BY  SUM (quantity) DESC)     AS r_num
         FROM       deliveryitem
         GROUP BY  item_no
    SELECT     i.description
    ,     r.total_quantity
    FROM     got_r_num     r
    JOIN     item          i     ON     r.item_no     = i.item_no
    WHERE     r.r_num     = 1
    ;If you want to do it without a sub-query:
    SELECT       MIN (i.description) KEEP (DENSE_RANK LAST ORDER BY SUM (di.quantity)
                        AS description
    ,       MAX (SUM (quantity))     AS total_quantity
    FROM       deliveryitem     di
    JOIN       item          i     ON     d1.item_no     = i.tiem_no
    GROUP BY  i.description
    ;If you do nested aggegate functions, then every column in the SELECT clause must be an aggregate applied to either
    (a) another aggregate, or
    (b) one of the GROUP BY expressions.
    That's why you got the ORA-00937 error.
    This second approach will only display one row of output, so If there is a tie for the item with the greatest total_quantity, only one description will be shown. The RANK method will show all items that had the highest total_quantity.
    It looks like the delivery table plays no role in this problem, but it there's some reason for including it, you can join it tpo either query above.
    Of course, unless you post test copies of your tables (CREATE TABLE and INSERT statements) I cn't test anything.
    Edited by: Frank Kulash on Nov 6, 2010 10:57 AM

  • How to store the value of sum of group in Crystal Report at the runtime!

    Hello all,
    I creates a Formula Field that hold the value of Sum of Group in Crystal Report. I would like to know how to store it in a variable and pass it to store procedure. Is it an option in Crystal report to do it. I knew that Crystal Report can cache the report for sharing. My detailed issue as following:
    - Created a Formula Field named TOTAL AMOUNT that calculated the complex expression. This TOTAL AMOUNT is dynamic based on group and variables.
    - I would like to store that value from TOTAL AMOUNT and pass it to the stored procedure parameter IN.
    Any helps are much appreciated. Thanks.

    I doubt that this is possible since it would only calculate this value once the report has data.  This sounds more like a report design question that should be asked over [here|SAP Crystal Reports;

  • Nested group function without group xmlagg

    I am getting nested group function without group by xmlagg when using the xmlagg function inside another xmlagg function. Find the table structure and sample data here,
    CREATE TABLE "TEST_TABLE"
       ("KEY" NUMBER(20,0),
        "NAME" VARCHAR2(50 ),
        "DESCRIPTION" VARCHAR2(100 )
       Insert into TEST_TABLE (KEY,NAME,DESCRIPTION) values (1,'sam','desc1');
       Insert into TEST_TABLE (KEY,NAME,DESCRIPTION) values (2,'max','desc2');
       Insert into TEST_TABLE (KEY,NAME,DESCRIPTION) values (3,'peter',null);
       Insert into TEST_TABLE (KEY,NAME,DESCRIPTION) values (4,'andrew',null);
    select
            XMLSerialize(document
            xmlelement("root",
             xmlagg(
               xmlelement("emp"          
               , xmlforest(Key as "ID")          
               , xmlforest(name as "ename")
               , xmlelement("Descriptions", 
               xmlagg(
                  xmlforest(description as "Desc")
           ) as clob indent
           ) as t   
          from test_table;Then i removed the xmlagg function from the above select query and used xmlelement instead
      select
            XMLSerialize(document
            xmlelement("root",
             xmlagg(
               xmlelement("emp"          
               , xmlforest(Key as "ID")          
               , xmlforest(name as "ename")
               , xmlelement("Descriptions",            
                  xmlforest(description as "Desc")
           ) as clob indent
           ) as t   
          from test_table;This is working fine, but xml created with empty elements for Descriptions element for key 3 and 4 which has null values. I need don't need Descriptions element in the xml when it has null value. Please help me to resolve this.

    You can do it with a correlated subquery :
    SQL> select xmlserialize(document
      2           xmlelement("root",
      3             xmlagg(
      4               xmlelement("emp"
      5               , xmlforest(
      6                   t.key as "ID"
      7                 , t.name as "ename"
      8                 , (
      9                     select xmlagg(
    10                              xmlelement("Desc", d.description)
    11                              order by d.description -- if necessary
    12                            )
    13                     from test_desc d
    14                     where d.key = t.key
    15                   ) as "Descriptions"
    16                 )
    17               )
    18             )
    19           ) as clob indent
    20         )
    21  from test_table t;
    XMLSERIALIZE(DOCUMENTXMLELEMEN
    <root>
      <emp>
        <ID>1</ID>
        <ename>sam</ename>
        <Descriptions>
          <Desc>desc1_1</Desc>
          <Desc>desc1_2</Desc>
          <Desc>desc1_3</Desc>
        </Descriptions>
      </emp>
      <emp>
        <ID>2</ID>
        <ename>max</ename>
        <Descriptions>
          <Desc>desc2_1</Desc>
          <Desc>desc2_2</Desc>
          <Desc>desc2_3</Desc>
        </Descriptions>
      </emp>
      <emp>
        <ID>3</ID>
        <ename>peter</ename>
      </emp>
      <emp>
        <ID>4</ID>
        <ename>andrew</ename>
      </emp>
    </root>
    Or an OUTER JOIN + GROUP-BY :
    select xmlserialize(document
             xmlelement("root",
               xmlagg(
                 xmlelement("emp"          
                 , xmlforest(
                     t.key as "ID"
                   , t.name as "ename"
                   , xmlagg(
                       xmlforest(d.description as "Desc")
                       order by d.description -- if necessary
                     ) as "Descriptions"
             ) as clob indent
    from test_table t
         left outer join test_desc d on d.key = t.key
    group by t.key
           , t.name
    ;Edited by: odie_63 on 11 juil. 2012 14:54 - added 2nd option

  • Limit a Pivot Table filter to just one group (Excel 2010)

    I use Excel 2010 and want to apply a filter to just one group of data within a Pivot Table.
    It appears that filters are applied to the entire Pivot table; is there a way to limit the scope of a filter so it is applied to just a single group of data (grouped using the group function within a Pivot). Alternatively could I apply a filter to just a
    selection of rows within the Pivot?
    I have tried breaking my pivot into separate tables and applying the filters individually but the tables interfere with each other when expanded/collapsed and generate the Excel "overlapping tables" error message.
    Any suggestions gratefully received.
    Regards
    Pete

    just use filter is no possible that apply a filter to one group. maybe slicers is a good choose.
    http://office.microsoft.com/en-us/excel-help/use-slicers-to-filter-pivottable-data-HA010359466.aspx
    KR

  • Filter table data without calling BAPI

    Hi all,
    How I can filter VC table without calling BAPI or other backend? The objective is to bring a large data only once and allow to user filtering of this data.
    The problem is that the filter options are dynamic so I can't use "hidden tables" workarownd.
    Any ideas?
    Thanks,
    Ola

    Hi,
    I think this is not possible, because you can only filter the data once with the filter element. If you use a BI query you can use filters. Maybe you can bring the data to a hidden table and get the data again from this table with different filter elements resp. dynamic filter values, but I think this is very tricky and not a good solution.
    Best Regards,
    Marcel

  • Recorset filter by url then group by

    I have a search results page that get its information via a
    complex form then their is a more details page which is filtered by
    the url i want to put another record set on the page which pick up
    the info from the URl but then sort the information from a feild
    which contains codes i want to select only part of the code ie
    first 3 digits of the code.
    i am using dreamweaver 8
    this is the code from the dreamweaver panel if i fillet them
    seprately they work but together i get no data can any give me a
    clue on how to filter by url then group by field if contains "text"
    SELECT *
    FROM all1
    WHERE product_name = 'MMColParam' AND product_id LIKE
    'testVariable'
    variables
    MMColParam 1 Request.QueryString("product_name")
    testVariable "%thr%" testVariable

    thanks !
    my URL call a template, so, is this the good url ? :
    <SAP_BW_URL ITEM='*TPL*' MULTI='X' HIDDEN='X' FILTER_NODE_IOBJNM_1='ZIS_PDT' FILTER_VALUE_1='C' CMD_1='ITEM=*TPL1*&MULTI=X&HIDDEN='>
    or did i must put it in the CMD like this ? :
    <SAP_BW_URL ITEM='*TPL*' MULTI='X' HIDDEN='X' CMD_1='ITEM=*TPL1*&MULTI=X&HIDDEN=&FILTER_NODE_IOBJNM_1='ZIS_PDT'&FILTER_VALUE_1='C''>
    another question,
    in my query, did the characteristic must be in "free characteristic" or in "filter" or nowhere ???
    thanks a lot

  • Reset Group Sum at group change .... Urgent......

    Hi,
    I ve 4 groups in my report as a,b,c,d . and the structure is
    a
    |--> b
    |-> c
    |-> d
    ie. group d is nested in c, c is nested in b , b is nested in a.
    I want sum of group d . But at the same time when any of groups a,b,c changes , sum should be reset .
    Plz let me know how to reset sum on changing any of the groups a,b,c in same hierarchy.

    Hi
    Try to set it in the properties of the sum.
    Ott Karesz
    http://www.trendo-kft.hu

  • Eliminating NULLs for SUM(current-group)

    I face the following problem:
    I have some NULL values in my data which I elimnated by a <?xdofx:decode(FIELD,'',0,FIELD)?>
    add. I have defined a summary field with <?sum (current-group()/FIELD)?> that results in "NaN" because of the NULLs.
    But decode doesn't work in the sum(c... ) !?
    Any help is appreciated.
    Dirk

    Hi,
    I didn't know about the to_number, that's useful to know.
    It get's a little ugly in your template but you can work around have the sum before the for-each. The answer is to have a for-each purely to create the sum. I've had to do it for a couple of templates.
    I usually put the code in a template to make it easier to read and the not put too much code in to a cell in a table. Try the following:
    <?template:t_sumdata?>
    <?for-each:xxx?>
    <?if:ELEMENT!=''?>
    add to variable
    <?end if?>
    <?end for-each?>
    <?end template?>
    The above code can go anywhere in your template, I normally put them at the end. To reference this just put
    <?call:t_sumdata?><?get variable value?>
    where you want the total to appear.
    Thanks
    Paul

  • I need script which will filter a set of groups by name, and then give a CSV with direct members

    I need script which will filter a set of groups by name, and then give a CSV with direct members
    say it like,
    $groupitems = Get-ADGroup -SearchBase "DC=fincaint,DC=local" -Filter {Name -like "*AppUsers"}
    ForEach ($groupitem in $groupitems)
            IF ($groupitem.objectClass -eq 'user')
       Get-ADUser $groupitem | FT Name, Email, City, Title | Export-Csv c:\member.csv
          IF ($groupitem.objectClass -eq 'group')
       Get-ADgroup $groupitem | FT GroupName, GroupDN | Export-Csv c:\member.csv

    Hi Dhiravia,
    It's been a while. How is it going? If the suggestion provided by ThmsRynr doesn't help, for scripting questions, in order to get better help, it's recommended that we ask for advice in the following scripting forum.
    The Official Scripting Guys Forum
    https://social.technet.microsoft.com/Forums/scriptcenter/en-US/home?forum=ITCG
    Best regards,
    Frank Shen
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact [email protected]

  • Can I filter search by authorisation group?

    We have 5 sales orgs e.g. Z001, Z002, Z003, Z004, Z005. Each employee belongs to one sales org only. When the user searches on accounts I want to filter the search by the sales org the employee belongs to.
    To test this I maintained the business partners and assigned the authorisation group Z001 to 5 of our customers in one sales org. I have also assigned the authorisation group Z002 to 5 of our customers in another sales org that I do not want displayed. For others I have left empty. I did this because it is not a practical solution for us to maintain an authorization group for every customer.
    In transaction PFCG I have maintained the authorization group B_BUPA_GRP with the entry Z001 as this is the sales org I want displayed for this role.
    When I search for the customers (with no search criteria) it does not appear to do any filtering at all as more than 5 records were found, which is not correct.
    When I run the trace (ST01) I find that for the 5 customers that have the authorization group Z001, it is allowed. This is correct. For the 5 customers with authorization group Z002, it is not allowed. This is correct. However for the customers without any authorisation group assigned it is allowed. This is not correct.
    How is it possible to not display customers without an authorisation group?
    Regards
    Declan

    Well Declan..you have to note this thing before going for this solution.
    The field you want to add as a hidden search parameter , should not be available on UI.
    Otherwise controlling the user will be very difficult.(Nevertheless, you can achieve it, but have to take lot of pains.)
    For example if you want to display partners belonging to a particular country say 'US',then add a record to GT_HIDDEN_PARAMETERS.
    DATA: ls_params   TYPE genilt_selection_parameter.
        ls_params-attr_name = 'COUNTRY'.
        ls_params-sign      = 'I'.
        ls_params-option    = 'EQ'.
        ls_params-low      = 'US'.
        APPEND ls_params TO gt_hidden_parameters.
    Implement this code in EH_ONSEARCH and then call super class. Standard code by default reads this gt_hidden_parameters.
    This is proprietary to BP_HEAD_SEARCH Component. If you have to implement this for some other componet then you should create an attribute gt_hidden_parameters and then read this internal table manually and manipulate the search criteria as is being done in standard code of method EH_ONSEARCH of BP_HEAD_SEARCH/SearchHelp.
    As I mentioned earlier COUNTRY attribute should not be available on UI.
    If Country was  available on UI, then imagine a case if user enters 'UK' as country and you have hard-coded inside to get only 'US'
    Then the result list have partners of 'US' despite user entering 'UK'. I mean to say the hidden parameters should not be available on UI.
    This way you can any valid hidden attributes by looking at the search object of the serach page in Model Browser.
    Cheers,
    Masood Imrani S.

  • Filters without Groups / Smart Objects

    I want to add a layer of scratches and dust marks that is at the top of the composition without having to create a group or smart object.  I tried creating a black layer with the opacity to 0 then applying a scratches and dusts mark, I also tried a empty smart object with 0 opacity, that didn't work either.  I'm hoping their is a technique to this ?

    then applying a scratches and dusts mark
    Filter > Noise > Dust & Scratches is supposed to help remove such things, not add them, so I’m not sure what exactly you mean.
    A blank Layer (or a white Layer set to Blend Mode Multiply) and painted on in black with appropriate Brush tips with some randomization and Scattering might help.
    Could you post an example of what you are after?

Maybe you are looking for