Count (case when) not working in sql

Hi All,
I am trying to find the count of members for a perticular date range, it seems not working correclty.
Could any one help me out.
here is the query...I am getting same output for all the cases..please help
Select
t
.MemberNbr,t.patcom
count(case
when
datediff(d,
mbrs.DischargeDate,
convert(datetime,convert(varchar(12),t.specificdateofservice),112))
between
-1
and
-365
then t.MemberNbr
else 0
end)as
edvisits365daysprior
count(case
when
datediff(d,
mbrs.DischargeDate,
convert(datetime,convert(varchar(12),t.specificdateofservice),112))
between 1
and 3
then t.MemberNbr
else 0
end)as
edvisits3Days
count(case
when
datediff(d,
mbrs.DischargeDate,
convert(datetime,convert(varchar(12),t.specificdateofservice),112))
between 1
and 30
then t.MemberNbr
else 0
end)as
edvisits30Days
count(case
when
datediff(d,
mbrs.DischargeDate,
convert(datetime,convert(varchar(12),t.specificdateofservice),112))
between 1
and 60
then t.MemberNbr
else 0
end)as
edvisits60Days
count(case
when
datediff(d,
mbrs.DischargeDate,
convert(datetime,convert(varchar(12),t.specificdateofservice),112))
between 1
and 90
then t.MemberNbr
else 0
end)as
edvisits90Days
--,*--membernbr,specificdateofservice,count( membernbr)--, specificdateofservice)as visitcount--, patcom
--Into #Tmp_PPCSEDCnt1
From
stg_tbl_InPatientPrepost Mbrs
join
#Tmp_MCCSEDVisits t
on
mbrs.MemberNbr=t.MemberNbr
--where UPPER(t.MR_Line_Desc) in ('FOP EMERGENCY ROOM - HOSPITAL', 'FOP EMERGENCY ROOM Urgent Care',
--'PROF ER VISITS AND OBSERVATION CARE')
group
by t.MemberNbr,t.patcom

You may replace 0 as NULL and see how it works for you?
eg:
count(case when datediff(d, mbrs.DischargeDate,
convert(datetime,convert(varchar(12),t.specificdateofservice),112)) 
between -1 and -365 thent.MemberNbr else NULL end)as edvisits365daysprior

Similar Messages

  • SELECT CASE WHEN not working?

    Hello, can't figure out why the following statement continues to return NULL values and seems to not recognize my case when portion?...
    INSERT tbl_Main
    select OrderID
     ,(select
      case
       when (b.OrderValue is null or b.OrderValue = '') then 'Y'
       else b.OrderValue
      end
     from tbl_OrderDetails b where b.OrderID = a.OrderID and b.DetailID = '7')
    AS OrderStatus
    from tbl_Order a
    Thanks in advanced.

    Please post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions and formatting rules. Temporal data should
    use ISO-8601 formats. Code should be in Standard SQL as much as possible and not local dialect. 
    This is minimal polite behavior on SQL forums. 
    1. The use of the “tbl-” prefix is a design flaw called “tibbling” and people will laugh at you for it. 
    2. Do not nest selects inside a select list; the performance stinks. 
    3. Why do you think “A”, "D” etc are good aliases that will make maintaining this code easier? Noobs do this is match the names of tape drives on old hardware! 
    4. Why do you think that treating a NULL and an empty string as the same is a good idea? Use a CHECK (order_value <> ''). 
    My guess is you could write this instead: 
    INSERT INTO Orders
    SELECT order_id, COALESCE (D.order_value, 'Y') AS order_status
     FROM Order_Details AS D 
    WHERE D.order_id = Orders.order_id 
      AND D.detail_id = '7')
    AS order_status; 
    But this still smells bad. A status is a state of being so it has a temporal component. Order details do not usually have an id; the item identifier (EAN, UPC, SKU, or whatever) is used. 
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • CASE WHEN not working

    Hello all,
    I need to reclassify some data based on the values in two columns, the logic to do this is:
    WHEN CC=X AND DC IS NULL OR DC IS NOT NULL THEN B
    WHEN CC IS NULL AND DC IS NOT NULL THEN B
    WHEN CC IS NULL AND DC IS NULL THEN NB
    This should be a simple CASE WHEN. I've tried to build this logic in all possible ways and results are incorrect! As you can see is not a complicated one,
    Please help!
    Nayeli

    WHEN CC=X AND DC IS NULL OR DC IS NOT NULL THEN B
    WHEN CC IS NULL AND DC IS NOT NULL THEN B
    WHEN CC IS NULL AND DC IS NULL THEN NB
    1 tip,put always in brackets,it is annoying but help logic.
    2.try to make it step by step
    case WHEN ( CC=X ) AND ( DC IS NULL) OR ( DC IS NOT NULL ) THEN B
    else
    case when....
    else........
    be careful
    ( CC=X ) =1
    ( DC IS NULL)=2
    ( DC IS NOT NULL ) =3
    u mean (1 and 2) or 3,(1) and (2 or 3) ......
    i hope i helped....
    http://greekoraclebi.blogspot.com/
    ///////////////////////////////////////

  • EXEC SP_EXECUTESQL not working in sql server 2014

    EXEC SP_EXECUTESQL not working in sql server 2014

    EXEC SP_EXECUTESQL not working in sql server 2014
    Hi Amar,
    What's the error when executing this stored procedure?
    I have tested it on my local environment, we can run this SP without any problems.
    Please provide us more information, so that we can make further analysis.
    Regards,
    Charlie Liao
    TechNet Community Support

  • False/True Case is not working. Please Help!

    Dear all,
    I attached my block diagram, one attachment refers to true case and the other refers to false case.
    My program runs like this: when i run the vi , after homing the motor (there is home.vi), DAQ is collecting the values in the while loop, and according to the DAQ's value, motor should run the False/True case but it does not
    As a result: true/false case is not working which is located at the outside of the loop(bottom side of the block diagram)
    When i put the the True/false inside the Loop(DAQ's loop) , then it is working. But this brings lots of problem, two of them is: 
    1-) When the DAQ values goes below to "50" then it turns to true case again,
    2-) The false case has stop.vi which cause to motor stop every iteration of the loop.
    So that is why i put True/False case out of the loop but now it is not working at all.
    Please answer, waiting response.
    Thank you,
    Have a nice day,
    Kind Regards.
    Attachments:
    OutloopTrueMode.pdf ‏432 KB
    OutofLoopNotWorking.pdf ‏443 KB

    Salander wrote:
    Dear GerdW,
    Thank you for reply, You can see my answers written with red.
    "As long as the case structure is located outside the loop it will not be called before the loop stops. THINK DATAFLOW!"
    - The case structure need to run same time with the loop, because as you can see from the attachments the case structure is also integrated with DAQ values.. loop is continuous till i press the stop button.  So what i understand that this case structure will not work because loop is continuous?? Cant we upgrade the vi. or do smthg that it can be able to work same time with the loop??
    Kind Regards.
    You have to place the case structure inside the while loop ( Any significance is there on placing the case outside the loop? ).
    Salander wrote:
    Dear GerdW,
    Btw. it would be much more useful to attach real pictures or, even better, the VI...
    Because most of the people dont have my "motor controller's labview drivers"  I attached as a PDF file which is very popular.
    Not Really * .png file ( vi snippet ) is much more popular here in Discussion Forum
    The best solution is the one you find it by yourself

  • Database Mail not working with SQL Server Agent

    I'm running SQL Server 2005 Standard edition 64 bit with SP2 on a 64 bit machine. 
    Database mail does not work with SQL Server Agent.  When I configure SQL Server Agent to use database mail the test email button is greyed out and inactive therefore I cannot send emails using operators or for jub success failure etc. 
    I've read that there was supposed to be a fix for this with SP1 but I have SP2 and still receive the same problem.  Please can somebody help as I do not wish to use SQL Mail as a work around due to this becomming redundant in future versions of SQL Server.
    Kind Regards

    The problems solved
    steps:
    1)we create a mail profile at at Managment->Database Mail ,of SQL Managment
    2)we set this account as "default" at Managment->Database Mail -> Configure Database Mail -> Manage profile security
    3)At tab "Alert System" of SQL Server Agent properties , we check the "Enable mail profile" , Mail System=Database Mail, Mail profile = "the profile we already create"
    4)we create a new operator at "Operators" of sql agent, where at "notification options" -> "Email name" we put the mail where we want to sent the agent the mails at failured job
    5)We go at a specific job, at tab "Notifications" ,we check the "email" check box and then we choose the operator we just create, at the text box next to check box.
    I hope not to forget something
    Thank You all for the help

  • "case when not m[1] is present then" outputs ORA-03113

    I find that "case when not m[1] is present then" outputs ORA-03113:
    Why?
    SQL> select * from v$version;
    BANNER
    Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Prod
    PL/SQL Release 10.2.0.1.0 - Production
    CORE    10.2.0.1.0      Production
    TNS for 32-bit Windows: Version 10.2.0.1.0 - Production
    NLSRTL Version 10.2.0.1.0 - Production
    select * from dual model
    dimension by(0 as d)
    measures(1 as m)
    rules(
    m[any] = case when not m[1] is present then 1 end);
    ORA-03113:Below one is alterNative solution.
    select * from dual model
    dimension by(0 as d)
    measures(1 as m)
    rules(
    m[any] = case when presentv(m[1],1,0) = 0 then 3 end);
    D  M
    0  3

    I get:
    ops$me%DB>  select * from dual model
      2    dimension by(0 as d)
      3    measures(1 as m)
      4    rules(
      5    m[any] = case when not m[1] is present then 1 end);
    select * from dual model
    ERROR at line 1:
    ORA-03002: operator not implemented
    Elapsed: 00:00:00.03
    ops$me%DB> select banner from v$version;
    BANNER
    Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bi
    PL/SQL Release 10.2.0.4.0 - Production
    CORE    10.2.0.4.0      Production
    TNS for IBM/AIX RISC System/6000: Version 10.2.0.4.0 - Productio
    NLSRTL Version 10.2.0.4.0 - Production

  • LIKE operator is not working in SQL Query in XML file

    Hi Gurus,
    LIKE operator is not working in SQL query in XML template.
    I am creating a PDF report in ADF using Jdeveloper10g. The XML template is as follows
    <?xml version="1.0" encoding="WINDOWS-1252" ?>
    <dataTemplate name="catalogDataTemplate" description="Magazine
    Catalog" defaultPackage="" Version="1.0">
    <parameters>
    <parameter name="id" dataType="number" />
    <parameter name="ename" dataType="character" />
    </parameters>
    <dataQuery>
    <sqlStatement name="Q1">
    <![CDATA[
       SELECT ename, empno, job, mgr from EMP where deptno=:id and ename LIKE :ename || '%']]>
    </sqlStatement>
    </dataQuery>
    <dataStructure>
    <group name="EmployeeInfo" source="Q1">
    <element name="EmployeeName" value="ename" />
    <element name="EMPNO" value="empno" />
    <element name="JOB" value="job"/>
    <element name="MANAGER" value="mgr" />
    </group>
    </dataStructure>
    </dataTemplate>
    if i pass the parameter value of :ename from UI, it doesn't filter. But if I give ename = :ename it retrieves the data. Can anyone help me why LIKE operator doesn't work here?
    Appreciate your help,
    Shyamal
    email: [email protected]

    Hi
    Well for a start, you are doing some very strange conversions there. For example...
    and to_char(a.msd, 'MM/DD/YYYY') != '11/11/2030'
    and to_char(a.msd, 'MM/DD/YYYY') != '10/10/2030'If a.msd is a date then you should e converting on the other side ie.
    and a.msd != TO_DATE('11/11/2030', 'MM/DD/YYYY')
    and a.msd != TO_DATE('10/10/2030', 'MM/DD/YYYY')Also, you may want to take into consideration nothing being input in :P2_ITEM_NUMBER like this...
    AND INSTR(a.item_number,NVL(:P2_ITEM_NUMBER,a.item_number)) > 0Is item number actually a number or char field? If it's a number, you want to explicitly convert it to a string for using INSTR like this...
    AND INSTR(TO_CHAR(a.item_number),NVL(TO_CHAR(:P2_ITEM_NUMBER),TO_CHAR(a.item_number))) > 0?
    Cheers
    Ben

  • (Substitution Variables) not working in "SQL Developer" Environment !!!!!!!

    this photo illustrate how that (Substitution Variables) not working in "SQL Developer" Environment :-
    http://www.imagehosting.com/show.php/1555180_ddddd.PNG.html
    any solve for this problem ?????!!!!!!!!!!

    There is a dedicated forum for SQL Developer related questions
    SQL Developer
    I should admit however, that query you have provided ( with substitution variables) works like a charme in my environment (SQL Developer 1.1.0.23 build 23.64)
    Best regards
    Maxim

  • File- Print not working from SQL Developer 1.2.1 Build MAIN-32.13

    File->Print not working from SQL Developer 1.2.1 Build MAIN-32.13.
    I downloaded sqldeveloper-1.2.1.3213.ZIP and extract to a local directory. From the extracted directory I ran ..\sqldeveloper\sqldeveloper.exe from Windows XP sp2. The program itself seems to run just fine but File-Print doesn't do anything. In Help-About, Java Platform is reported as 1.5.0_06 and Oracle IDE is 1.2.1.3213. I'm not sure where to look for what is causing the problem.
    Thanks

    I hadn't tried CTRL-P before but I did today. On the first attempt, I saw a small jump in the memory usage for sqldeveloper.exe as reported in Windows Task Manager. Otherwise, there was no change. A second CTRL-P in the same session produced a further bump but subsequent attempts in the same session produced no further change in CPU or Memory Usage.
    Using Task Manager to monitor this further, I tried File->Print again and saw that sqldeveloper would periodically climb to 1 or 2 percent CPU and consume a little more memory. After a minute or so, though, all activity stops again.
    I do not get a print dialog box from SQLDeveloper using either CTRL-P or File->Print

  • Process validation for test case is not working

    I' am using SQL Developer EAR 3.0.02.83. The is a test case defined which uses "Query returns rows" with Select count(*) from dual;
    It should return a row an that way fulfill the test.
    but when running the testcase I get the result ERROR due to:
    Query returns rows not succesful: null
    How can I find the reason? Is this a bug?
    Even other types of validation do not work, they always give null and the overall result ERROR.

    Thanks for your reply. Unfortunately our procedure returns in some cases null values, so that a unit test is not possible.
    I need to ckeck the results of the function, but not to compare them with fixed values, rather something like {VALUE$} LIKE 'x%Y'.
    I'am afraid there is no solution.
    When can I hope the relaese version to be available?

  • CLOB with case statement not working getting error

    Can anyone help on this
    I write this sql
    select Case when to_clob(PROPERTY) = 'is_intradesk=Y' then 'Internal' end
    from JPM_CP;
    Where PROPERTY column is clob column and its giving the error "ORA-00932: inconsistent datatypes: expected - got CLOB"
    Is it not possible to use clob columns with case or decode !

    Its working but it does not fulfill my purpose
    In you answer it is looking for position right! means, does the column contain the value('Intradesk=Y' ) or not. means
    I am looking for exact match with CLOB column values, that is Clob column(PROPERTY) contains the exact value that value which I am comparing with i.e 'Intradesk=Y'
    I need this
    select * from table where clob_column = 'value' (exact).
    Edited by: sajalkdas on Feb 4, 2011 3:28 PM

  • Case statement Not working with Oracle version 10g

    Below is code , which works on 11r2 but not on 10g.
    declare
    v1 VARCHAR2(200);
    begin
    select version into v1 from DBA_REGISTRY WHERE COMP_NAME LIKE '%Catalog Views%';
    CASE
          WHEN v1 like '10.2%' THEN
    DBMS_OUTPUT.PUT_LINE('it is  10.2');
    dbms_streams_auth.grant_admin_privilege('GGADMIN');
          WHEN v1 like '11.1%' THEN
    DBMS_OUTPUT.PUT_LINE('it is  11.1');
    dbms_streams_auth.grant_admin_privilege('GGADMIN');
    EXECUTE IMMEDIATE 'grant become user to GGADMIN';
          WHEN v1 like '11.2.0.3%' THEN
    DBMS_OUTPUT.PUT_LINE('it is  11.2.0.3');
    dbms_goldengate_auth.grant_admin_privilege('GGADMIN');
        END CASE;
    end;
    /I dont know when i run code in 10.2 it still looks for dbms_goldengate_auth
    and error out.
    dbms_goldengate_auth.grant_admin_privilege('GGADMIN');
    ERROR at line 18:
    ORA-06550: line 18, column 1:
    PLS-00201: identifier 'DBMS_GOLDENGATE_AUTH.GRANT_ADMIN_PRIVILEGE' must be declared
    ORA-06550: line 18, column 1:
    PL/SQL: Statement ignoredif I comment dbms_goldengate_auth it returns perfect result.
    it is  10.2
    PL/SQL procedure successfully completed.
    Elapsed: 00:00:00.03Is there any other way around ????
    Edited by: 949509 on Jan 27, 2013 6:57 PM

    949509 wrote:
    Can you please tell me How i can execute dynamic sql via execute immediate.In a very simialr was as you did the grant of become user in your code. SOmething like:
    declare
       v1          VARCHAR2(200);
       l_grant_str VARCHAR2(1000);
    begin
       select version into v1 from DBA_REGISTRY WHERE COMP_NAME LIKE '%Catalog Views%';
       CASE
          WHEN v1 like '10.2%' THEN
             DBMS_OUTPUT.PUT_LINE('it is  10.2');
             l_grant_str := 'dbms_streams_auth.grant_admin_privilege(''GGADMIN]'')';
          WHEN v1 like '11.1%' THEN
             DBMS_OUTPUT.PUT_LINE('it is  11.1');
             l_grant_str := 'dbms_streams_auth.grant_admin_privilege(''GGADMIN'')';
             EXECUTE IMMEDIATE 'grant become user to GGADMIN';
          WHEN v1 like '11.2.0.3%' THEN
              DBMS_OUTPUT.PUT_LINE('it is  11.2.0.3');
             l_grant_str := 'dbms_goldengate_auth.grant_admin_privilege(''GGADMIN'')';
       END CASE;
       execute immediate l_grant_str;
    end;John

  • Count into variable not working in procedure

    I'm writing a simple procedure in a package. Based on Record count I'm inserting record into other table.
    count(fielname) alwways returns zero. But the same SQL statement works fine when I just execute sql statement out side of procedure in SQL window.
    supplierid, userid fields are varchar(20)
    L_CNTSUPP NUMBER;
    SELECT count(SUPPLIERID)
    INTO L_CNTSUPP
    FROM TBLSEQUENCE TS, TBLUSER TU
    WHERE ltrim(rtrim(TS.SUPPLIERID)) = ltrim(rtrim(TU.INFO_1))
    AND ltrim(rtrim(TU.USERID)) = ltrim(rtrim(L_USERID));
    DBMS_OUTPUT.put_line(L_CNTSUPP);
    Please advice.

    Hello,
    Try this:
    SELECT count(*)
    INTO L_CNTSUPP
    FROM TBLSEQUENCE TS, TBLUSER TU
    WHERE ltrim(TS.SUPPLIERID) = ltrim(TU.INFO_1)
    AND ltrim(TU.USERID) = ltrim(L_USERID);
    DBMS_OUTPUT.put_line(L_CNTSUPP);A few points: you do not need an RTRIM when using VARCHAR since it's automatically RTRIMmed, but you should be using VARCHAR2 in Oracle - VARCHAR is for Oracle's own internal use and may change without notice. You only need LTRIM if you've spaces to the left of the data.

  • [BUG] "Open declaration" in some cases does not work

    If object name has the different register of letters then "Open declaration" in context menu does not work. But in the same case "Popup describe" in context menu works fine.
    Oracle SQL Developer 3.1.07
    Version 3.1.07
    Build MAIN-07.42
    Edited by: Roman on 19.04.2012 3:48

    I also would like to see some explanation when is it planned to make this feature work :)

Maybe you are looking for

  • How to Populate Sender Id in FM SO_NEW_DOCUMENT_SEND_API1

    Hi Friends, I am using FM SO_NEW_DOCUMENT_SEND_API1 for sending an email to the users. Though everything is working fine but I want to set the sender id. For example any user may run the report but in sender name it should come accountspayable at the

  • Warning message on MRP view

    Hi consultants, I have a material that is specified as "External Procurement" Material.   It is because it's a Subcon material.  In line with this, a production version is maintained due to some business process requirement, which the system allows. 

  • Meta-key in terminal

    I am using a Macbook with a norwegian keyboard. The keyboard doesn't have symbols such as | or ~, so I have to use the Option key to produce them. In terminals, I have the ability to set Option to behave as a meta-key which gives me the full function

  • Cannot place photos in events anymore

    I don't have that many photos or events (7,000, ok, a lot) but I now have discovered that I cannot place photos into events anymore, and I cannot create new events. Previously I had photos organized into both events (by country) and into photo albums

  • Waiting for Dreamweaver CS4, OR migrating to another developer?

    Hi: Not long time ago when DWMX came out I got very excited. At last something real came out. I tried Codecharge, some coffeecup tools and many many other programs that claimed that they could help us develop websites with less coding and more thinki