Multiple count query

I'm trying to write a function to compare two different counts.
I have patient on multiple drugs...some drugs are allergy drugs and at least one allergy drug must be marked as primary.
select count(drug_role) as vAllergyCount, count(primary_flag) as PF, ap.patient_id
from ae_all_drugs aed, ae_patient ap
where drug_role = 'Allergy'
and aed.patient_id = ap.patient_id
and ap.patient_id like '2012%'
group by ap.patient_id,primary_flag
order by ap.patient_id
when grouped by patient id and primary flag I would receive a record like this:
VAlllergyCount | PF | patient_id
1 | 0 | 2012AB1
3 | 1 | 2012AB1
If i only group by patient_id I get this (which is what I want):
VAlllergyCount | PF| patient_id
4 | 1 | 2012AB1
But if I try to compare the two:
IF vAllergyCount > 1 and PF = 1 THEN 'SUCCESS' ELSIF 'FAIL'
I receive the error message "exact fetch returns more than requested number of rows" becuase the results are really my first query.
Can anyone help me re-write my query to compare the values?
P.S. I'm very new to this and this forum and I apologize for not inserting code tags. I don't know how.

Hi,
979105 wrote:
Thank you for your hlep.
I need to write a function because the SQL query is going to be used as an edit check for another program. So yes, it will have to worth my time.
You are correct. I have a patient on multiple drugs. I want to know if there is at least one allergy drug (drug_role) > 1 if there is at least ONE primary allergy drug.
I did initially write my function with the patient_id as an input value. Why would I not need the vAllergyCount or the pf if that is an argument?If all you want to know is 'SUCCESS' or 'FAIL', then write a query that produces 'SUCCESS' or 'FAIL'. Inside the query, it may be handy to have something like vAllergyCount or pf, but that doesn't mean that they will be returned by the query, or that you need PL/SQL variables for them.
Here's my original function:That's a PROCEDURE, not a function. Sometimes, people use the word "procedure" lossely, to mean any kind of stored code, including functions, but never the other way around.
\Don't forget to put another \ tag at the end of the formatted section.
\ tags are supposed to occur in pairs. If you have an odd number of \ tags, the last one has no effect, and is displayed as regular text.
PROCEDURE COUNT_ALLERGY_MED (
     ivPatient_ID IN VARCHAR2,
     ovErrorText          OUT     VARCHAR2 )
IS
     vCase_ID          VARCHAR2 (25);
     vSusCount           NUMBER (3);
     vSuspectMed          VARCHAR2 (1);
     --vPrimaryFlag     VARCHAR2(1);
cursor c1 is
     select count(*) as vSusCount
     from ae_suspect_drugs aed
     where drug_role = 'S'
     and aed.case_id = ivCase_ID
     --group by ivcase_id;
BEGIN
open c1;
fetch c1 into vSusCount;
close c1;
IF vSusCount < 1 /*AND vPrimaryFlag IS NULL*/ THEN
     ovErrorText := 'Suspect Drug Count is less than 1' || 'SusCount: ' || vSusCount;
     ELSIF vSusCount = 1 /*AND vPrimaryFlag IS NULL*/ THEN
     ovErrorText := 'Suspect Drug count is equal to 1' || 'SusCount: ' || vSusCount;
     ELSIF vSusCount > 1 /*AND vPrimaryFlag IS NULL*/ THEN
     ovErrorText := 'Suspect Drug count is greater than 1 ' || 'SusCount: ' || vSusCount;
     ELSE
     ovErrorText := 'All criteria met';
END IF;
END COUNT_SUSPECT_MED;It seems like it would be more convenient to have a FUNCTION, rather than a PROCEDURE; that way you could call the function directly in a SQL statement (e.g., in the WHERE clause of a query or DML statement) as well as in PL/SQL.
The procedure you posted seems to be quite a bit differetn from the problem you asked eariler.
Here's one way you might write a fucntion for the earlier problem:CREATE OR REPLACE FUNCTION count_allergy_med
( ivPatient_ID IN VARCHAR2
RETURN VARCHAR2
IS
return_str VARCHAR2 (50);          -- To be returned
BEGIN
SELECT CASE
     WHEN COUNT (drug_role) > 1
          AND COUNT (primary_flag) = 1
          THEN 'SUCCESS'
          ELSE 'FAIL'
     END     
INTO return_str
FROM ae_all_drugs     aed
,      ae_patient           ap
WHERE drug_role          = 'Allergy'
AND     aed.patient_id      = ap.patient_id
AND     ap.patient_id     = ivPatient_ID;
RETURN return_str;
END count_allergy_med;
Notice that there are no columns in the result set, nor variables in the function, that correspond to vAllergyCount or pf.
The function above returns 1 of 2 possible values.  You couold just as well write a function that had 4 possible outcomes, or 4 basic results, each containing a variable number, such asSuspect Drug Count is less than 1. SusCount: 0
I'm not sure why you would want such as result, since 0 is the only possible count that is less than 1, but it's easy enough to produce results like that if you really want them.
Once again, if you'd like help, post a clear example of what you want.  Include CREATE TABLE and INSERT statements for some sample data.  Post some code where you might use the function that you're thinking of.  Give a couple of different arguments for that functuion, and the results you would want for each argument given the same sample data.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

Similar Messages

  • Query to display multiple counts in the result

    Hi,
    I need to be able to display multiple counts for different items in the single result set:
    Here is the simplified schema:
    I have 2 tables:
    STATEMENT table:
    ===============
    statement_pk number,
    department varchar2(20)
    STATEMENT_INFO table:
    ===================
    statement_info_pk number,
    statement_fk number
    is_statement_done varchar2(1)
    is_statement_locked varchar2(1)
    I need to display counts of how many records where done and how records where locked in the
    single output:
    Statement_PK Department NumberOfStatementsDone# NumberofStatementsLocked#
    1          ABC_dept          3                    5
    2          DEF_dept          4                    8
    3          XYZ_dept          7                    2
    The following does not work:
    SELECT
    s.statement_pk,
    s.department,
    COUNT(r.statement_info_pk ) NumberOfStatementsDone# ,
    COUNT(rr.statement_info_pk ) NumberOfStatementsLocked#
    FROM STATEMENT s ,
    STATEMENT_INFO r,
    STATEMENT_INFO rr
    WHERE
         s.statement_pk = r.statement_fk
         AND     s.statement_pk = rr.statement_fk
         AND      is_statement_done = 'Y'      AND rr.is_statement_locked = 'Y'
    GROUP BY statement_pk, s.department
    I was trying to work with analytic function but could not figured it out either.
    Please help
    Thanks,
    Ia.

    this would be something like:
    SQL> r
      1  select statement_pk,
      2         department,
      3         sum(decode(is_statement_done, 'Y', 1, 0)) statement_done,
      4         sum(decode(is_statement_locked, 'Y', 1, 0)) statement_locked
      5  from   statement_info,
      6         statement
      7  where  statement_fk = statement_pk
      8* group by statement_pk, department
    STATEMENT_PK DEPARTMENT           STATEMENT_DONE STATEMENT_LOCKED
               1 ABC_dept                          4                1
               2 DEF_dept                          6                2
               3 XYZ_dept                          1                2
    SQL> Message was edited by:
    Leo Mannhart
    Craig you were faster

  • Incorrect count query

    I'm using CursoredStream to fetch a large result set. When doing a cursor.size() Toplink generates the wrong count query. I do have group value functions in the query as shown below.
    For e.g. this is the cursor query:
    --- Actual select query ---
    SELECT t0.AWARD_ID, t0.AWARD_NUMBER, t0.FINAL_AMOUNT, t2.NAME,
    SUM(t1.REPORT_AMOUNT), t4.FISCAL_YEAR, t5.DESCRIPTION
    FROM REF_ENTITY t6, T_CODE t5, SOL t4, APP t3, APP_VERSION t2, SUBG t1,
    AWARD t0
    WHERE ((((t4.FISCAL_YEAR = '1993') AND (t6.REF_ENTITY_ID = 5)) AND (t4.SUBG_
    REPORT = 'Y')) AND ((t5.T_CODE_ID = t0.T_CODE_ID_STATUS) AND ((t2.APP_ID = t3.A
    PP_ID) AND ((t6.REF_ENTITY_ID = t4.REF_ENTITY_ID) AND ((t4.SOL_ID = t3.SOL_ID)
    AND ((t3.APP_ID = t0.APP_ID) AND (t0.AWARD_ID = t1.AWARD_ID)))))))
    GROUP BY t0.FINAL_AMOUNT, t0.AWARD_ID, t0.AWARD_NUMBER, t4.FISCAL_YEAR, t5.D
    ESCRIPTION, t2.NAME ORDER BY t0.AWARD_NUMBER ASC
    The count query generated by Toplink is:
    SELECT COUNT(*)
    FROM REF_ENTITY t4, AWARD t3, APP t2, SOL t1, SUBG t0
    WHERE ((((t1.FISCAL_YEAR = ?) AND (t4.REF_ENTITY_ID = ?))
    AND (t1.SUBG_REPORT = 'Y')) AND ((t4.REF_ENTITY_ID = t1.REF_ENTITY_ID)
    AND ((t1.SOL_ID = t2.SOL_ID) AND ((t2.APP_ID = t3.GMS_APP_ID)
    AND (t3.AWARD_ID = t0.AWARD_ID)))))
    I have to provide my own ValueReadQuery to get the correct count in the above case. Are there any rules for determining when we have to explicitly provide our own count query?
    cheers
    p.s: Toplink version 9.0.3.4

    Abe,
    This sounds like a bug. I assume you are using a ReportQuery to generate the initial SQL. You should only have to provide a ValueReadQuery to a cursored query when using SQL, stored-procedure, or to optimize what is being generated.
    This looks like the group-by on your ReportQuery is being ignored on the size query. The best plan is to submit this to support with the TopLink code used and the information provided in this post.
    In the mean time the work-around of providing your own query is probably the best solution.
    Doug

  • Count Query Performance

    How can we improve the perfromace of a count query?
    Suppose I have a table A that holds more than 50 million rows.
    Now if i want to count the no of rows which is the best one
    1) Select count(*) from A.
    Definitely not as it is doing a full table scan
    2) Select count(primary_key) from A.
    3) Select count(row_id) from A.
    One more question whats the difference between select count(*) from table_name and select count(1) from table_a. Many people suggest count(1) and i dont see any reason though.
    Kindly guide me.

    > Please see my points 1,2 and 3.
    Can this change the execution plan (path) of the CBO in anyway?
    1. count rows
    2. count rows using primary key
    3. counting rows using physical row addresses
    The fact is that the rows, and all the rows, need to be counted. The CBO will choose the most "attractive" I/O path - i.e. the smallest one, the one with the least amount of I/O. It does not need tricks like COUNT(1) or COUNT(PK) or COUNT(ROWID) in order to make an appropriate decision.
    Example:
    SQL> create table tab1 nologging as select level as ID, LPAD('*',4000,'*') as STUFF from dual connect by level <= 10000;
    Table created.
    SQL> set autotrace on
    Running a SELECT COUNT(*) without any alternate I/O paths (no indexes exist)
    SQL> select count(*) from tab1;
    COUNT(*)
    10000
    Execution Plan
    Plan hash value: 899213575
    | Id | Operation | Name | Rows | Cost (%CPU)| Time |
    | 0 | SELECT STATEMENT | | 1 | 2306 (4)| 00:00:28 |
    | 1 | SORT AGGREGATE | | 1 | | |
    | 2 | TABLE ACCESS FULL| TAB1 | 9982 | 2306 (4)| 00:00:28 |
    Note
    - dynamic sampling used for this statement
    Statistics
    28 recursive calls
    0 db block gets
    10087 consistent gets
    10000 physical reads
    0 redo size
    208 bytes sent via SQL*Net to client
    238 bytes received via SQL*Net from client
    2 SQL*Net roundtrips to/from client
    0 sorts (memory)
    0 sorts (disk)
    1 rows processed
    Creating an PK index
    SQL> alter table tab1 add constraint pk_tab1 primary key(id) using index;
    Table altered.
    Running the same SELECT COUNT(*) - but the CBO now sees that the PK index
    is smaller and cheaper to scan than scanning the table
    SQL> select count(*) from tab1;
    COUNT(*)
    10000
    Execution Plan
    Plan hash value: 1796789124
    | Id | Operation | Name | Rows | Cost (%CPU)| Time |
    | 0 | SELECT STATEMENT | | 1 | 9 (23)| 00:00:01 |
    | 1 | SORT AGGREGATE | | 1 | | |
    | 2 | INDEX FAST FULL SCAN| PK_TAB1 | 9982 | 9 (23)| 00:00:01 |
    Note
    - dynamic sampling used for this statement
    Statistics
    194 recursive calls
    0 db block gets
    131 consistent gets
    20 physical reads
    0 redo size
    222 bytes sent via SQL*Net to client
    238 bytes received via SQL*Net from client
    2 SQL*Net roundtrips to/from client
    5 sorts (memory)
    0 sorts (disk)
    1 rows processed
    SQL>

  • Problem with multiple counter plan containing running hrs and no of months

    Hey gurus,
    In my project the preventive maintenance of compressor is such that it is performed after 500 hrs or 6 months whichever comes first. Now i ve created a cycle set cosisting of 500 hrs and 6 months. In the multiple counter plan i ve assigned a counter to the plan for calculating 500 hrs and chosen the link as OR. I scheduled the plan and given the start date as 01.05.09. Now I am facing the following problem:
    Suppose my counter value reaches the 500 mark on 01.08.09. Now a maintenance order is generated. My client now wants that the next order should be generated after the counter reading reaches 1000 or the date reaches 01.02.10, ie, the order should be generated for next 500hrs or NEXT 6 MONTHS from
    the date of completion of first cycle, whichever comes first.
    Pls help....
    Regards,
    Abhishek

    Hi
    If u have scheduled ur plan according to cycle set. It will take the Point of contact as 6 months.
    OK
    Ex : Cycle set : 500 hrs and 6 months, maintained OR functions
    i have entered the measurement reading as 500.. thats why, it gives the call for todays date...
    see the next date will be after 6 months... If u update the measuring point only, it will open a order... otherwise.. once u have scheduled it for 6 months.. once in 6 months it will give a order...
    1     11.05.2009               0     New start  Save to call
    2     07.11.2009     07.11.2009          0     Scheduled  Hold
    3     06.05.2010     06.05.2010          0     Scheduled  Hold
    4     02.11.2010     02.11.2010          0     Scheduled  Hold
    5     01.05.2011     01.05.2011          0     Scheduled  Hold
    6     28.10.2011     28.10.2011          0     Scheduled  Hold
    7     25.04.2012     25.04.2012          0     Scheduled  Hold
    Schedule for a long period.. u will be able to understand the scenario...
    - Pithan

  • Getting run time error for multiple counter plan

    Hi Friends,
    Its very critical issue,wherein i am getting run time error for multiple counter plan.
    Explanation:While try to change the Call horizon or scheduling period of the counter based plan through IP42 or IP15,systam allowing me to change the data but while saving also i am getting "Maintenance plan has changed" message and once come to the back of the transaction instantly i am getting pop up window saying that "Express document get terminated".However we have been maintaining copy of this data in another client wherein we are not getting any Run time error.
    Please find the screen shots for your reference and please let me know how to fix the issue.
    Regards,
    Srinika

    Hi,
         Please check reason for update termination in Transaction code SM13.

  • First time scheduling using IP30 for Multiple Counter plan

    Hi,
    I created a multiple counter plan with Cycle set as 6months/ 300 Operations.
    I intend to start the job early and updated the Planned Counter date as  1st Sep 2014.I maintained Lead Float as 10 days.
    When I run IP10, call is generated successfully. But when I execute IP30, no call is generated.
    We have not activated enhanced functionality of Multiple Counter plans.
    I checked all the parameters and everything seemd to be fine. In IP30, I checked the check boxes - Rescheduling & Immediate start of all.
    In the field, Interval for Call Objects, I ran with blank value, 30 days value. But in both the cases, call is not generated.
    I want to generate calls using IP30 only as there are lot of multiple counter plans. Can anybody suggest a solution to this issue?

    Hello
    As you intended to use cycle set functionality please activate enhanced functionality of Multiple Counter plans
    Br
    Rakesh

  • Count query taking time

    I have a query -->select c1,c2,c3 from table1 . This query takes only few milliseconds. But when I take count from the same query i.e. when I execute select count(c1,c2,c3) from table1 then it takes a very long time (about 1 min). The table1 contains about 25000 rows. Please help to improve performance of Count query.

    Satej wrote:
    I have a query -->select c1,c2,c3 from table1 . This query takes only few milliseconds. But when I take count from the same query i.e. when I execute select count(c1,c2,c3) from table1 then it takes a very long time (about 1 min).Classic misperception of Toad, SQL Navigator and similar tool users. All these tools fetch just first result screen and show time it took to fetch just that and not the time to fetch all rows. And in order to count you need to fetch all rows.l That is why select count(*) takes longer. But 1 min for 25000 rows is a bit long. Check execution plan to see what is going on.
    SY.

  • Counter base maintenance and multiple counter maintenance

    Hi
    With refering to the counter base order generated in the system, i have confused.
    We have the plans 100, 200, 300 to max 2000 Hours. The task lists are assigned. The maintenance plan annual estimate is 4000 Hours (i dont know why its required if the measurment documents are in use) ..
    The system is regularely generating the orders eventhough we have measurement docuements upto 300 Hours. Last week we have no measurement updates.
    Can you give me the logic, functionality of the performance maintennace. I have read SAP help which is not explaining in practical manner.
    Also how to work for multiple counter maintenance. We have to do for DAY (30 Days, 60 days. 180, 360 Days) Wise or Hour wise (300, 900, 1500, 3500, 7000 Hours maintenance. Can you tell me how to work for this on single maintennace plan..since our equipment also only one.

    Hi,
    This appears to be a typical multiple counter plan situation consisting of performance based and time based elements. The performance cycles are based on operating hours and time is the elapsed days.
    The relevant section of SAP Help is - [here|http://help.sap.com/saphelp_erp60_sp/helpdata/en/d8/e06a1f7e9c144fbb3a3ed0c38bc38a/frameset.htm]
    See point 3-Scheduled date calculation. In particular:
    The annual performance recorded for the counters and the most up-to-date counter reading are used to calculate the corresponding planned date.
    Annual Estimate is used to calculated planned date meaning that calls can occur before the actual counter readings are reached.
    -Paul

  • Query of multiple counts with conditions or multiple querys

    I have this demo table
    create table qtyrtu
    rtunam varchar2(10) not null,
    entity varchar2(10) not null,
    linked number(3) not null
    Insert into qtyrtu values ('02vh1', 'zdvh', 100);
    Insert into qtyrtu values ('02vh2', 'zdvh', 0);
    Insert into qtyrtu values ('02eh1', 'zdvh', 0);
    Insert into qtyrtu values ('02sh1', 'stvh', 100);
    Insert into qtyrtu values ('02sh1', 'stvh', 0);
    Insert into qtyrtu values ('02sh1', 'stvh', 100);
    Insert into qtyrtu values ('02tx', 'zdch', 100);
    Insert into qtyrtu values ('02ta', 'zdch', 100);And my result expected would be the next one.
    Entity | Count(rtunam linked by 100) | Count (rtunam linked by 0)
    STVH    2   1
    ZDCH    2   0   
    ZDVH    1   2The problem is that I don't know how to query the 0, when I do my query(by column) it shows this:
    select entity, count(rtunam) from qtyrtu where linked = 100 group by entity order by entity asc;
    STVH    2
    ZDCH    2   
    ZDVH    1
    select entity, count(rtunam) from qtyrtu where linked = 0group by entity order by entity asc;
    STVH     1
    ZDVH     2And I need to show all the counts( even the 0)
    Regards

    Hi,
    Thanks for posting the sample data and the results; that really helps!
    Here's one way:
    SELECT    UPPER (entity)                    AS upper_entity
    ,       COUNT (CASE WHEN linked = 100 THEN 1 END)     AS cnt_100
    ,       COUNT (CASE WHEN linked = 0   THEN 1 END)     AS cnt_0
    FROM       qtyrtu
    GROUP BY  entity
    ;It looks like rtunam plays no role in this problem: is that right?
    You already know how to get the separate column results, using a WHERE clause to ignore certain rows, but you can't use a WHERE clause here, because to want to ignore different rows for the two COUNT columns. A CASE expression can be like a WHERE clause that applies only to one column.

  • Query with multiple counts

    Hi, I have a question..I have some data that I need to get counts on within the same table with different criteria. For example, I have a table with work queues and I need to count up work_queues based on dates which is on field date_due. I need to find a count of all of a particular work_queue by date. Below is some of the code I have come up with but is not returning the correct counts that I need:
    select t.wh_id, count(t.work_q_id) Last10Days ,count(tt.work_q_id) Last20Days
    from t_work_q t full outer join t_work_q tt on (t.wh_id=tt.wh_id) and (t.work_status=tt.work_status) and (t.work_type=tt.work_type)
    where t.wh_id='20'
    and t.work_status='C'
    and t.work_type='08'
    and t.date_due > sysdate-10
    and tt.date_due > sysdate-20
    group by t.wh_id
    Separately this query works fine
    Select wh_id,count(work_q_id) Last20Days
    from t_work_q
    where wh_id='20'
    and work_type in ('08','14')
    and work_status='C'
    and date_due > sysdate-10
    group by wh_id
    What I need to do is try to query these where there are counts in each column for the specified date. Above shows sysdate-10 and I would like to get a column each for Last30Days, etc. Any help would be appreciated. Thanks.

    Actually, I figured it out...for those who wanted to know (don't there were):
    select wh_id, count(work_q_id) as numberof,
         sum(case when date_due>sysdate-10 then 1 else 0 end) as Last10Days,
         sum(case when date_due>sysdate-20 then 1 else 0 end) as Last20Days,
         sum(case when date_due>sysdate-30 then 1 else 0 end) as Last30Days,
         sum(case when date_due>sysdate-60 then 1 else 0 end) as Last60Days,
         sum(case when date_due>sysdate-90 then 1 else 0 end) as Last90Days
    from t_work_q
    where work_type in ('08','14')
    and work_status='C'
    group by wh_id
    Thanks to those who would have helped.

  • Customer Count Query

    Hello All
    I need help in writing a Optimized query .
    Scenario :
    We have several customers across multiple vendors .We want to get Customercount by vendor for a year 
    In this scenario we wanted to claculate 
    Customer Count for Vendor 
    Example 
    2014  Kroger(Vendor) has 100 customers
    2014  Target(Vendor) has 50 customers
    I wanted to see out of those 100 customers for Kroger who were not customer of kroger in 2012 and 2013 but customer of target
    Similarly  out of those 50 customers for Target who were not customer of target in 2012 and 2013 but customer of
    kroger
    In 2012 same customer might have bought with different vendor.We are calculating new to vendor 
    C1  2012   Kroger 100
    C1  2012   Walmart 100
    C2  2012   target 100
    C2  2012   Kroger 100
    C1  2014   target 100
    C2  2014   Kroger 100
    C2  2014   target 100
    C2  2014   walmart 100
    In this case C1 is customer count for target   as he did not buy with target but with other vendors
    and c2 canot be counted towarsd kroger or walmart becauase be bought with both of them but can be counterd towarrds walmart as he did not buy with walmart
    I am trying to write a query to get 2012 and 2013 data for all vendors and then join with 2014 data set
    but the thing is i am getting wrong count 
    Please let me know

    this?
    SELECT Vendor,
    YEAR(DATEADD(yy,DATEDIFF(yy,0,Datefield),0)) AS Yr,
    COUNT(CustomerID) AS CustomerCount,
    COUNT(CASE WHEN Cnt = 0 THEN CustomerID ELSE NULL END) AS FirstTimeCustomerCount
    FROM Table t
    OUTER APPLY (SELECT COUNT(*) AS Cnt
    FROM Table
    WHERE CustomerID = t.CustomerID
    AND DATEDIFF(yy,0,Datefield) < DATEDIFF(yy,0,t.Datefield)
    AND Vendor = t.Vendor)
    GROUP BY Vendor,DATEDIFF(yy,0,Datefield)
    Please Mark This As Answer if it solved your issue
    Please Vote This As Helpful if it helps to solve your issue
    Visakh
    My Wiki User Page
    My MSDN Page
    My Personal Blog
    My Facebook Page

  • Attn: PDO Experts (COUNT query)

    This is an example of the type of a PHP/MySQL query I use to display dynamic web pages. This particular query is associated with a website/section that displays URL's like MySite/People/Crazy_Horse, where Crazy_Horse = both $MyURL and a value in the field URL, table people...
    $res = mysql_query("SELECT COUNT(URL)
      FROM people
      WHERE URL = '$MyURL' AND Site = 'PX'
      OR '$MyURL' = CONCAT('Washington/', URL) AND Site = 'SM'");
      if (!$res) {
        die('Invalid query: ' . mysql_error());
    $result = mysql_result($res, 0);
    // PART 2 - Interpret the results...
    switch ($result)
    case 1:
    // include related files
    break;
    case 0:
    // include 404 NOT FOUND error message
    break;
    default:
    // multiple entries; deal with as needed
    break;
    Now I'm trying to learn PDO, and I assumed the simplest queries would be the simplest to convert to PDO. To my surprise, many online references say PDO can't perform COUNT queries! As I understand it, all the PDO queries that do this sort of thing are workarounds. After consulting several tutorials and forums and trying several scripts, I still don't have a working model. This is what I'm trying at the moment:
    I start out with my PDO database connection (replacing "USERNAME" and "PASSWORD" with my username and password, of course...
    try {
        $db = new PDO('mysql:host=localhost;dbname=db_new;charset=utf8', 'USERNAME', 'PASSWORD');
    } catch (PDOException $e) {
        print "Error!: " . $e->getMessage() . "<br/>";
        die();
    The above code is on a separate file that's included in every page on my website.
    I then have this code on a downstream file...
    $sql= "SELECT URL FROM people
    WHERE URL = '$MyURL'";
    $stmt = $pdo->prepare($sql);
    $stmt->execute();
    $total = $stmt->rowCount();
    But it doesn't work, and there's no error message to indicate what the problem is. (However, if I modify my username or password in the connection script, I do get an error message referring to my database connection.) Once I do get it to work, I assume I can finish the job by simply replacing $result with $total...
    switch ($total)
    case 1:
    // include related files
    break;
    case 0:
    // include 404 NOT FOUND error message
    break;
    default:
    // multiple entries; deal with as needed
    break;
    Can anyone tell me what I'm doing wrong, and how I can fix it?
    Thanks.

    How does this post relate to Web Design?   Any ideas?

  • Need some help with count query

    Hello,
    I'm terrible @ oracle, so bear with me. I am trying to use the count function with my query but it counts rows from different tables.
    I want my query to basically add a column from another table but have it not be a part of the count.
    Say, table1 table2 table3. My count is right between the first two tables (Buyers,5).But since in table3 there are duplicate values(or accounts in this case(3), the count multiples by that many (15).
    I need it to read Buyers,5,account #. I've tried distinct and a union but to no avail.
    Help me please.

    If I understand you correctly, you want to count the records in table1 and table2 which have a one-to-one relationship, but you need to display additional data from table3 which has a one-to-many relationship. If this is correct, you need to use an in-line view to join table1 and table2 then join that in-line view to table3 to display the data from it. Something along the lines of:
    SELECT v.col1, v.col2, v.col3, v.col4, v.cnt, t3.col1 t3col1, t3.col2 t3col2
    FROM (SELECT t1.col1, t1.col2, t2.col1 col3, t2.col2 col4, COUNT(*) cnt
          FROM table1 t1, table2 t2
          WHERE <join conditions between t1 and t2> and
                <other conditions if required>
          GROUP BY t1.col1, t1.col2, t2.col1, t2.col2) v,
         table3 t3
    WHERE <join conditions between v and t3>
          <other conditions if required>John

  • To retrieve the Multiple Count of Records for Multiple types

    Hi Can some one help me in this:
    I have a talbe (MyTable) in which a column(Column 1) will have values as (Value1, Value2 , Value3, Value4 and Value5) for Multiple Records .
    I need to write a query which can give me the count of All the existing Records with the values(Value1, Value2 , Value3, Value4 and Value5) by a Single Query.The Resulting Table should have the Columns as :(Value1, Value2 , Value3, Value4 and Value5) with the Corresponding Counts in the Table.
    Thanks in Advance,
    vijay kumar k.
    Plz help me asap as it is very much linked with my Work..

    Hello
    Well, it always helps if you can post a create table statement, some test data, and the result you are expecting....it doesn't take long and you'll be much more likely to get a quick response from someone who has some time in between things that very much related to their work...
    create table dt_test_values(col1 varchar2(10))
    insert into dt_test_values values('value1')
    insert into dt_test_values values('value1')
    insert into dt_test_values values('value2')
    insert into dt_test_values values('value2')
    insert into dt_test_values values('value2')
    insert into dt_test_values values('value3')
    insert into dt_test_values values('value3')
    insert into dt_test_values values('value4')
    insert into dt_test_values values('value4')
    insert into dt_test_values values('value4')
    insert into dt_test_values values('value4')
    insert into dt_test_values values('value5')
    insert into dt_test_values values('value5')
    insert into dt_test_values values('value6')
    insert into dt_test_values values('value7')
    insert into dt_test_values values('value7')
    SQL> SELECT
      2     SUM(DECODE(col1,'value1', 1, 0)) value1,
      3     SUM(DECODE(col1,'value2', 1, 0)) value2,
      4     SUM(DECODE(col1,'value3', 1, 0)) value3,
      5     SUM(DECODE(col1,'value4', 1, 0)) value4,
      6     SUM(DECODE(col1,'value5', 1, 0)) value5,
      7     SUM(DECODE(col1,'value6', 1, 0)) value6,
      8     SUM(DECODE(col1,'value7', 1, 0)) value7,
      9     SUM(DECODE(col1,'value8', 1, 0)) value8
    10  FROM
    11     dt_test_values
    12  /
       VALUE1    VALUE2    VALUE3    VALUE4    VALUE5    VALUE6    VALUE7    VALUE8
            2         3         2         4         2         1         2         0HTH
    David

Maybe you are looking for