Unique counts - across a group by

I am attempting to count unique patients that stay in the hospital. But they want the count by months. I only want the patient to count in the first month. is there a good way to do this.
for example if I have a table like:
CREATE TABLE "PATIENT_CHARGES"
     "SERVICE_DATE" DATE,
     "VISIT_NO" VARCHAR2(20 BYTE)
Insert into PATIENT_CHARGES (SERVICE_DATE,VISIT_NO) values (to_date('01-JAN-12','DD-MON-RR'),'1');
Insert into PATIENT_CHARGES (SERVICE_DATE,VISIT_NO) values (to_date('01-FEB-12','DD-MON-RR'),'5');
Insert into PATIENT_CHARGES (SERVICE_DATE,VISIT_NO) values (to_date('01-FEB-12','DD-MON-RR'),'3');
Insert into PATIENT_CHARGES (SERVICE_DATE,VISIT_NO) values (to_date('01-MAR-12','DD-MON-RR'),'5');
Insert into PATIENT_CHARGES (SERVICE_DATE,VISIT_NO) values (to_date('01-JAN-12','DD-MON-RR'),'2');
Insert into PATIENT_CHARGES (SERVICE_DATE,VISIT_NO) values (to_date('01-FEB-12','DD-MON-RR'),'4');
and I run a query like:
SELECT TO_CHAR(SERVICE_DATE, 'YYYYMM') AS SERVICE_CY_MONTH, COUNT(DISTINCT VISIT_NO)
FROM PATIENT_CHARGES
GROUP BY TO_CHAR(SERVICE_DATE, 'YYYYMM')
I get:
201201     2
201202     3
201203     1
My total is 6. But I only have 5 patients. The 5th person stayed Feb - March . So although its a distinct count, it is by month, so they get double counted. What's my best way to get around this?

Frank Kulash wrote:
Hi,
br**** wrote:
Sorry its not really a unique patient identifier - that would be a medical record number, this is more a counter for each visit they have.Okay, so where I used visit_no, you should use whatever identifies the patient.Frank:
Hopitals are odd places. In many ways, we do not care about patients, only visits (well, at least for counting/billing purposes). The medical reord number (MRN) uniquely identifies a patient across all of their interactions with the hospital, while a visit number uniquely identifies a particular interaction with the hospital. In most of the hopital systems I have seen patient is an attribute of visit, not the other way around.
Certainly in my hospital, we would count distinct visits rather than patients. That is, if a patient with MRN 123 was here on visit number 9865 in February, and again on visit number 10023 in March, we would count that twice, but if visit 10023 extended into April, it would depend on the specific question being asked whehter we aould count that as one or two.
John

Similar Messages

  • Supplier data across business groups

    Our business group is currently using only Core HR and there are several contractors/contingent workers in the system. What is the best way to capture the supplier name? Right now, it is captured in some DFF but I want to use the supplier name field in the supplier tab of assignment form. There are other business groups in the same instance for different countries and they are using the purchasing module and have defined suppliers for their use which I am able to see in the list of values for supplier field in my business group.
    I want to suggest our HR folks to start using the supplier field instead of capturing this information in some DFF. Will there be any negative implications of doing this? Is supplier data shared across business groups? If I define suppliers for our business group purposes, will the other business groups be able to see our values?
    Please suggest.
    Thanks
    Jay
    Edited by: Jay on Oct 10, 2012 8:02 AM

    Hi Ranay,
    Approvals using Position Hierarchy can be used across Business Group. But specific to purchasing module not 100% sure.
    Thanks
    AshokP

  • Count() for each group, but only groups having 1+ element like... AND all elements like...

    There are tables(and columns) like:
    'Clients'(clientID)
    'Houses' (houseID)
    'Visits' (clientID, houseID, visit_date)
    'Contracts'(contractID, houseID, clientID, rentDate_from, rentDate_end)
    I have problem with writing MS SQL query of this kind:
    how many visits to houses did each client, before renting one of them?
    Its easy to count total number of Visits for each client, listing all visits + group by clientID and selecting count(*) for each group.
    Lets say this is select_1, and select_2 is listing all Contracts for all clients.
    Select_1 is not answer, because count must be performed only on groups, which:
    -have at least 1 row "like" row in select_2 (it means that at least one of visited houses was rented, because it can happen that client visited few houses, but rented other, not visited house). my idea for this is comparing select_1 and select_2 with:
    "where s1.clientID=s2.clientID and s1.houseID=s2.houseID"
    -each group must have all rows(visits) with date of same day or earlier than contract date
     maybe: "datediff(day, s1.visit_date, s2.rentDate_from) >= 0"

    In future, please provide proper DML, DDL and example data, like I have for you below.
    DECLARE @clients TABLE (clientID INT, name VARCHAR(20))
    INSERT INTO @clients (clientID, name)
    VALUES (1, 'Jonathan'),(2, 'Christopher'),(3, 'James'),(4, 'Jean-Luc'),(5, 'William')
    DECLARE @houses TABLE (houseID INT, address VARCHAR(20))
    INSERT INTO @houses (houseID, address)
    VALUES (1, 'NX01'),(2, 'NCC 1701'),(3, 'NCC 1071A'),(4, 'NCC 1701D'),(5, 'NCC 1701E')
    DECLARE @visits TABLE (clientID INT, houseID INT, visitDateTime DATETIME)
    INSERT INTO @visits (clientID, houseID, visitDateTime)
    VALUES (1,1,'2001-01-01 12:13:14'),
    (2,2,'2001-01-02 12:13:14'),
    (3,2,'2001-01-01 12:13:14'),(3,3,'2001-01-01 12:13:14'),
    (4,4,'2001-01-01 12:13:14'),(4,5,'2001-01-01 12:13:14'),
    (5,4,'2001-01-01 12:13:14'),(5,5,'2001-01-01 12:13:14')
    DECLARE @contracts TABLE (contractID INT IDENTITY, houseID INT, clientID INT, rentStartDate date, rentEndDate date)
    INSERT INTO @contracts (houseID, clientID, rentStartDate, rentEndDate)
    VALUES (1,1,'2001-01-02',NULL),(2,2,'2001-01-02',NULL),(3,3,'2001-01-02',NULL),(4,4,'2001-01-02',NULL),(5,5,'2001-01-02',NULL)
    SELECT contractID, c.houseID, c.clientID, rentStartDate, rentEndDate, cl.clientID, name, h.houseID, address, COUNT(v.clientID) AS visits
    FROM @contracts c
    LEFT OUTER JOIN @clients cl
    ON c.clientID = cl.clientID
    LEFT OUTER JOIN @houses h
    ON c.houseID = h.houseID
    LEFT OUTER JOIN @visits v
    ON c.clientID = v.clientID
    AND c.rentStartDate >= v.visitDateTime
    GROUP BY contractID, c.houseID, c.clientID, rentStartDate, rentEndDate, cl.clientID, name, h.houseID, address

  • How to create & Assign unique Qualification level and Groups(Each trans.)

    Hi,
    While working on CRM_LEAD i have observed that i cannot create unique Qualification level or Groups/origins for each transactions, if i add one more Qualification level or Groups/origins in existing table it is reflecting in all corroseponding Leads.
    Please tell me how to create seperate Qualification level and Groups/origins for each Transaction, else we can use Authorisation Object for this.
    Please resolve.
    Regurds,
    Dipesh.

    Hi Chirag,
    I've read the following link, but the question is....
    - Where is the link to create transport groups? That is my only question It's as easy as that
    Found it...sorry I knew it was easy
    Edited by: Gonçalo Mouro Vaz on Dec 20, 2007 5:13 PM

  • SCE 8000 i can not assign unique counter for service

    Hi!
    1. Create new service http://clip2net.com/s/1jg2x
    2. Try to assign unique counter for service, but a field inactively http://clip2net.com/s/1jg45
    how it to fixed?

    Hi!
    I think you're running out of counter index for the subscriber usage counter, it's 0-31.
    Please uncheck the check box from other existing service and try that again?
    Thanks!
    Tomo

  • CR - giving total transaction count for few groups and 0 for few groups.

    For the column "No of First Call Resolution" I have to count no of interactions based on the Interaction Result, the formula is
    COUNT(Interaction_ID) WHERE INTERACTION_RESULT = 'FCR'
    For which, I wrote the below formula
    If {14CICustomerInteractions_query.Interaction Result} = "FCR" then Count ({14CICustomerInteractions_query.Interaction_ID})
    I have 33,232 interactions on the particular day I selected. When I try to group up and do the calculations it is giving total transaction count for few groups and 0 for few groups.
    Need Solution

    Hi,
    What field is the report grouped on?
    If you wish to find the no of interactions based on some condition and display it for every group, then here's what you need to do:
    1) Create this formula and place this on the details section:
    whileprintingrecords;
    numbervar c;
    If {14CICustomerInteractions_query.Interaction Result} = "FCR" then
    c := c + 1;
    2) Create another formula and place this one on the Group Footer:
    whileprintingrecords;
    numbervar c;
    3) Create this formula to reset the variable and place this on the Group Header:
    whileprintingrecords;
    numbervar c := 0;
    Let me know how this goes!
    -Abhilash

  • How to make National Identifier unique across business group

    Hi Everyone,
    We're into R12.1.3 Oracle HRMS
    HR: Make National Identifier Optional = No
    HR: NI Unique Error or Warning = Error
    HR:Cross Business Group = Yes
    HR: Cross BG Duplicate Person Check = Yes
    The idea is to make raise an ERROR whenever user encounter a duplicate national identifier
    Thank You
    Elmer

    Hi Elmer,
    Which legislation code are you running? It should be set to 'I'. Check with
    select application_short_name, legislation_code, status from hr_legislation_installations;
    If it is not set some post install steps may have been missed.
    Regards,
    Joe

  • How do I count specific, smaller groups of information in one large table?

    Hello all,
    I have a feeling the answer to this is right under my nose, but somehow, it is evading me.
    I would like to be able to count how many photos are in any specific gallery. Why? Well, on my TOC page, I thought it would be cool to show  the user how many photos were in any given gallery displayed on the screen as part of all the gallery data I'm presenting. It's not necessary, but I believe it adds a nice touch. My  thought was to have one massive table containing all the photo information and another massive table containing the gallery  information, and currently I do. I can pull various gallery information  based on user selections, but accurately counting the correct number of  images per gallery is evading me.
    In my DB, I have the table, 'galleries', which has several columns, but the two most relevant are g_id and g_spe. g_id is the primary key and is an AI column that represents also the gallery 'serial' number. g_spec is a value that will have one of 11 different values in it (not relevant for this topic.)
    Additionally, there is the table, 'photos', and in this table are three columns:  p_id, g_id and p_fname. p_id is the primary key, g_id is the foreign key (primary key of the 'galleries' table) and p_fname contains the filename of each photo in my ever-expanding gallery.
    Here's the abbreviated contents of the galleries table showing only the first 2 columns:
    (`g_id`, `g_spec`, etc...)
    (1, 11, etc...),
    (2, 11, etc...),
    (3, 11, etc...),
    (4, 11, etc...),
    (5, 12, etc...),
    (6, 13, etc...)
    Here's the contents of my photos table so far, populated with test images:
    (`p_id`, `g_id`, `p_fname`)
    (1, 1, '1_DSC1155.jpg'),
    (2, 1, '1_DSC1199.jpg'),
    (3, 1, '1_DSC1243.jpg'),
    (4, 1, '1_DSC1332.jpg'),
    (5, 1, '1_DSC1381.jpg'),
    (6, 1, '1_DSC1421.jpg'),
    (7, 1, '1_DSC2097.jpg'),
    (8, 1, '1_DSC2158a.jpg'),
    (9, 1, '1_DSC2204a.jpg'),
    (10, 1, '1_DSC2416.jpg'),
    (11, 1, '1_DSC2639.jpg'),
    (12, 1, '1_DSC3768.jpg'),
    (13, 1, '1_DSC3809.jpg'),
    (14, 1, '1_DSC4226.jpg'),
    (15, 1, '1_DSC4257.jpg'),
    (16, 1, '1_DSC4525.jpg'),
    (17, 1, '1_DSC4549.jpg'),
    (18, 2, '2_DSC1155.jpg'),
    (19, 2, '2_DSC1199.jpg'),
    (20, 2, '2_DSC1243.jpg'),
    (21, 2, '2_DSC1332.jpg'),
    (22, 2, '2_DSC1381.jpg'),
    (23, 2, '2_DSC1421.jpg'),
    (24, 2, '2_DSC2097.jpg'),
    (25, 2, '2_DSC2158a.jpg'),
    (26, 2, '2_DSC2204a.jpg'),
    (27, 2, '2_DSC2416.jpg'),
    (28, 2, '2_DSC2639.jpg'),
    (29, 2, '2_DSC3768.jpg'),
    (30, 2, '2_DSC3809.jpg'),
    (31, 2, '2_DSC4226.jpg'),
    (32, 2, '2_DSC4257.jpg'),
    (33, 2, '2_DSC4525.jpg'),
    (34, 2, '2_DSC4549.jpg'),
    (35, 3, '3_DSC1155.jpg'),
    (36, 3, '3_DSC1199.jpg'),
    (37, 3, '3_DSC1243.jpg'),
    (38, 3, '3_DSC1332.jpg'),
    (39, 3, '3_DSC1381.jpg'),
    (40, 3, '3_DSC1421.jpg'),
    (41, 3, '3_DSC2097.jpg'),
    (42, 3, '3_DSC2158a.jpg'),
    (43, 3, '3_DSC2204a.jpg'),
    (44, 3, '3_DSC2416.jpg'),
    (45, 3, '3_DSC2639.jpg'),
    (46, 3, '3_DSC3768.jpg'),
    (47, 3, '3_DSC3809.jpg'),
    (48, 3, '3_DSC4226.jpg'),
    (49, 3, '3_DSC4257.jpg'),
    (50, 3, '3_DSC4525.jpg'),
    (51, 3, '3_DSC4549.jpg');
    For now, each gallery has 17 images which was just some random number I chose.
    I need to be able to write a query that says, tell me how many photos are in a specific photoset (in the photos table) based on the number in galleries.g_id  and photos.g_id being equal.
    As you see in the photos table, the p_id column is an AI column (call it photo serial numbers), and the g_id column assigns each specific photo to a specific gallery number that is equal to some gallery ID in the galleries.g_id table. SPECIFICALLY, for example I would want to have the query count the number of rows in the photos table whose g_id = 2 when referenced to g_id = 2 in the galleries table.
    I have been messing with different DISTINCT and COUNT methods, but all seem to be limited to working with just one table, and here, I need to reference two tables to acheive my result.
    Would this be better if each gallery had its own table?
    It should be so bloody simple, but it's just not clear.
    Please let me know if I have left out any key information, and thank you all in advance for your kind and generous help.
    Sincerely,
    wordman

    bregent,
    I got it!
    Here's the deal: the query that picks the subset of records:
    $conn = dbConnect('query');
    $sql = "SELECT *
            FROM galleries
            WHERE g_spec = '$spec%'
            ORDER BY g_id DESC
            LIMIT $startRow,".SHOWMAX;
    $result = $conn->query($sql) or die(mysqli_error());
    $galSpec = $result->fetch_assoc();
    picks 3 at a time, and with each record is an individual gallery number (g_id). So, I went down into my code where a do...while loop runs through the data, displaying the info for each subset of records and I added another query:
    $conn = dbConnect('query');
    $getTotal = "SELECT COUNT(*)
                FROM photos
                WHERE g_id = {$galSpec['g_id']}
                GROUP BY g_id";
    $total = $conn->query($getTotal);
    $row = $total->fetch_row();
    $totalPix = $row[0];
    which uses the value in $galSpec['g_id']. I didn't know the proper syntax for including it, but when I tried the curly braces, it worked. I altered the number of photos in each gallery in the photos table so that each total is different, and the results display perfectly.
    And as you can see, I used some of the code you suggested in the second query and all is well.
    Again, thank you so much for being patient and lending me your advice and assistance!
    Sincerely,
    wordman

  • Single Item Master across Business Groups

    Hi Gurus,
    Client wants to implement single item master across the business groups (BG).
    Does this require set up of HR Profile for allowing Cross Business groups?
    Is there any other setting that needs to be done (in addition to traditional Inv Org definition)?
    Appreciate your early response.
    Thanks,
    Sudarshan

    Sudarshan
    I think you need to setup Hr security profile only if you are using that. If not you just need to enable the profile value for cross business group. This is required just in case if an employee needs to be picked up in the lov in an item attribute (I don't remember whether there is one) from diff BG.Also move order approvals need to be tested if you are using that feature.
    In general I think anything that need to do with employees need to be tested.
    Thanks
    Nagamohan

  • Error in query with COUNT expression and Group By Clause

    Hi
    I have this query that when run gives me the following error:
    SQL command not properly ended:
    The code is as below:
    SELECT
              st_enrollment.student_id ,
              ce_family_member.last_name ,
              st_enrollment.grade_level ,
              ce_family_member.DATE_OF_BIRTH ,
              ce_family_member.GENDER,
              at_hourly_attendance_records.ABSENCE_REASON_CODE,
              at_hourly_attendance_records.CALENDAR_DATE,
              COUNT(st_enrollment.student_id) AS days_absent
              FROM
                      at_hourly_attendance_records,
                      ce_family_member,
                      st_enrollment
              WHERE
              st_enrollment.student_id = at_hourly_attendance_records.student_id
             AND ce_family_member.student_id = st_enrollment.student_id
                AND st_enrollment.school_id = 705
                AND st_enrollment.school_year = 2006
                AND st_enrollment.district_number = 1000
                AND at_hourly_attendance_records.ATTENDANCE_STATUS = 'A'
                AND at_hourly_attendance_records.CALENDAR_DATE < '16-MAR-06'
              GROUP BY st_enrollment.student_id,
                       ce_family_member.last_name
                         st_enrollment.grade_level ,
                         ce_family_member.DATE_OF_BIRTH ,
                         ce_family_member.GENDER,
                         at_hourly_attendance_records.ABSENCE_REASON_CODE,
                         at_hourly_attendance_records.CALENDAR_DATE;
           All suggestions are gratefully acknowledgment, Thanks in advance

    Thanks a lot. In fact I discovered it myself and I am immensely grateful to you for pointing the error..

  • Using count function with grouped records

    Hi all,
    This seems like it should be real easy but I have yet to figure out a simple way to do this.
    Suppose I want to count Opportunities that are grouped by Sales Rep. At run-time I am filtering this list with a parameter for Sales Stage and created date.
    I've simplified this greatly, but here's what my setup looks like now:
    Sales Rep* ---------Count*_
    <?for-each-group:Opportunity[SalesStage=param1 and Created>param2];./salesrep?>
    <?salesrep?>-------<?count(current-group()/Id)?>
    <?end for-each-group?>
    Total_
    The only solution I have so far to get my grand total is to create a variable and keep a running total which I'll then display in the Total column. While it works, it seems like there should be an easier way, like doing a simple count(Id) to get the grand total. But since the Total appears after the end for-each-group, I lose the filter that was applied to the group so that count is invalid.
    Any thoughts from the experts?
    Thanks!

    To get grand total
    use
    <?count(/Oppurtunity[SalesStage=param1 and Created>param2]/Id)?>since you did not mention the complete xml, i assumed, Opportunity as the Root.
    if not, put the full path from the root.
    if you give some xml sample, and explain the output you wanted, we can fix it immediately.
    go thru these too..some thing can be pulled from here .
    http://winrichman.blogspot.com/search/label/Summation%20In%20BIP
    http://winrichman.blogspot.com/search/label/BIP%20Vertical%20sum

  • SCOM Powershell get alert count for specific groups

    Hello good people,
    im looking for a powershell script (to use in powershell widget):
    ive got 3 groups which generate alerts, for example group1 group2 group3
    now i need to get all new alerts and closed alerts per group
    groupid  new  closed
    group1    12     100
    group2    10       50
    group3    3         6
    thx for your help in advanced

    you may consider using the following powershell cmdlet to count number of closed alert
    $gp1closed=get-scommonitoringobject|where-object{$_.displayname -eq 'group1'} | get-scomalert | whereobject$_.resolutionstate -eq '255'} |measure
    $gp1open=get-scommonitoringobject|where-object{$_.displayname -eq 'group1'} | get-scomalert | whereobject$_.resolutionstate -eq '0'} |measure
    $gp2closed=get-scommonitoringobject|where-object{$_.displayname -eq 'group2'} | get-scomalert | whereobject$_.resolutionstate -eq '255'} |measure
    $gp2open=get-scommonitoringobject|where-object{$_.displayname -eq 'group2'} | get-scomalert | whereobject$_.resolutionstate -eq '0'} |measure
    $gp3closed=get-scommonitoringobject|where-object{$_.displayname -eq 'group3'} | get-scomalert | whereobject$_.resolutionstate -eq '255'} |measure
    $gp3open=get-scommonitoringobject|where-object{$_.displayname -eq 'group3'} | get-scomalert | whereobject$_.resolutionstate -eq '0'} |measure
    'Group1' + '  '+ $gp1open + '  '+ $gp1closed
    'Group2' + '  '+ $gp2open + '  '+ $gp2closed
    'Group3' + '  '+ $gp3open + '  '+ $gp3closed
    Roger

  • Counting rows and group by

    Hi
    in query below
    WITH AUX_CONSULTORA AS (SELECT T2.CD_CONSULTORA,
                                         T2.CD_TIPO_ESTRUTURA_COMERCIAL,
                                         T2.CD_ESTRUTURA_COMERCIAL,
                                         T2.NM_CICLO_INICIO,
                                         T2.DC_NOME_CONSULTORA
                                    FROM T_CONSULTORA_INDICADA T1,
                                         T_CONSULTORA          T2
                                   WHERE T1.CD_CONSULTORA_INDICADA =
                                         T2.CD_CONSULTORA
                                     AND T1.CD_CONSULTORA_INDICANTE =
                                        4701040 --- CONSULTORA INDICANTE
                                     AND T2.NM_CICLO_INICIO <=
                                        200802 --- CICLO ATUAL
                                     AND T2.NM_CICLO_INICIO >=
                                         200716 --- TRES CICLOS ANTERIORES
                                  )SELECT                                                       
                                 DC_NOME_CONSULTORA,
                                  W1.CD_CONSULTORA,
                               NM_CICLO_INICIO,
                               W2.NM_CICLO_OPERACIONAL,
                               w2.vl_indicador
                         FROM AUX_CONSULTORA           W1,
                               T_EC_PESSOA_PERFIL_CICLO W2
                        WHERE W1.CD_TIPO_ESTRUTURA_COMERCIAL =
                              W2.CD_TIPO_ESTRUTURA_COMERCIAL
                          AND W1.CD_ESTRUTURA_COMERCIAL =
                              W2.CD_ESTRUTURA_COMERCIAL
                          AND W2.CD_CONSULTORA = W1.CD_CONSULTORA
                          AND W2.CD_PERFIL = 1
                          AND W2.CD_INDICADOR = 2
                          AND W2.NM_CICLO_OPERACIONAL <=  200802
                          AND W2.NM_CICLO_OPERACIONAL >=  200716
                          AND W2.NM_CICLO_OPERACIONAL >=  W1.NM_CICLO_INICIO
                          AND W1.NM_CICLO_INICIO >200716
                        ORDER BY W1.DC_NOME_CONSULTORA ASC;
    DC_NOME_CONSULTORA                       CD_CONSULTORA NM_CICLO_INICIO NM_CICLO_OPERACIONAL      VL_INDICADOR
    CRISTIANE MARIA MARQUES SUCUPIRA              38178923          200802               200802              0.00
    ELIONITA DE MATOS COSTA                       39218910          200801               200801              0.00
    ELIONITA DE MATOS COSTA                       39218910          200801               200802              1.00
    IBRANDINA LOPO MONTALVAO                      38176661          200717               200717              0.00
    IBRANDINA LOPO MONTALVAO                      38176661          200717               200801              0.00
    IBRANDINA LOPO MONTALVAO                      38176661          200717               200802              0.00
    JANAINA NOBRE DE MENEZES JORDAO RAMOS         38072777          200801               200801              0.00
    JANAINA NOBRE DE MENEZES JORDAO RAMOS         38072777          200801               200802              0.00
    JOCINELIA DE SOUZA LEITE                      38518490          200717               200802              0.00
    JOCINELIA DE SOUZA LEITE                      38518490          200717               200801              1.00
    JOCINELIA DE SOUZA LEITE                      38518490          200717               200717              0.00
    WALLACE DE OLIVEIRA XIMENES                   41824407          200717               200717              0.00
    WALLACE DE OLIVEIRA XIMENES                   41824407          200717               200801              1.00
    WALLACE DE OLIVEIRA XIMENES                   41824407          200717               200802              2.00
    I must to count distinct CD_CONSULTORA , in example above there are 6
    I did SELECT COUNT(DISTINCT) work fine , but now I must to Count WHEN
    W1.NM_CICLO_INICIO = 200716 and W2.NM_CICLO_OPERACIONAL = 200717 and in this cycle (200717) w2.vl_indicador =0 or W2.NM_CICLO_OPERACIONAL = 200801 and w2.vl_indicador =0
    Some know how can to do it ?
    see result for W1.NM_CICLO_INICIO =200716
    WITH AUX_CONSULTORA AS (SELECT T2.CD_CONSULTORA,
                                         T2.CD_TIPO_ESTRUTURA_COMERCIAL,
                                         T2.CD_ESTRUTURA_COMERCIAL,
                                         T2.NM_CICLO_INICIO,
                                         T2.DC_NOME_CONSULTORA
                                    FROM T_CONSULTORA_INDICADA T1,
                                         T_CONSULTORA          T2
                                   WHERE T1.CD_CONSULTORA_INDICADA =
                                         T2.CD_CONSULTORA
                                     AND T1.CD_CONSULTORA_INDICANTE =
                                        4701040 --- CONSULTORA INDICANTE
                                     AND T2.NM_CICLO_INICIO <=
                                        200802 --- CICLO ATUAL
                                     AND T2.NM_CICLO_INICIO >=
                                         200716 --- TRES CICLOS ANTERIORES
                                  )SELECT                                                       
                                 DC_NOME_CONSULTORA,
                                  W1.CD_CONSULTORA,
                               NM_CICLO_INICIO,
                               W2.NM_CICLO_OPERACIONAL,
                               w2.vl_indicador
                         FROM AUX_CONSULTORA           W1,
                               T_EC_PESSOA_PERFIL_CICLO W2
                        WHERE W1.CD_TIPO_ESTRUTURA_COMERCIAL =
                              W2.CD_TIPO_ESTRUTURA_COMERCIAL
                          AND W1.CD_ESTRUTURA_COMERCIAL =
                              W2.CD_ESTRUTURA_COMERCIAL
                          AND W2.CD_CONSULTORA = W1.CD_CONSULTORA
                          AND W2.CD_PERFIL = 1
                          AND W2.CD_INDICADOR = 2
                          AND W2.NM_CICLO_OPERACIONAL <=  200802
                          AND W2.NM_CICLO_OPERACIONAL >=  200716
                          AND W2.NM_CICLO_OPERACIONAL >=  W1.NM_CICLO_INICIO
                          AND W1.NM_CICLO_INICIO =200716
                        ORDER BY W1.DC_NOME_CONSULTORA ASC;
    DC_NOME_CONSULTORA                       CD_CONSULTORA NM_CICLO_INICIO NM_CICLO_OPERACIONAL      VL_INDICADOR
    ANA GLORIA DIAS DE CARVALHO                   43048927          200716               200802              2.00
    ANA GLORIA DIAS DE CARVALHO                   43048927          200716               200801              1.00
    ANA GLORIA DIAS DE CARVALHO                   43048927          200716               200717              0.00
    ANA GLORIA DIAS DE CARVALHO                   43048927          200716               200716              0.00
    ELAINE MARIA DE SANT ANNA                     43985238          200716               200717              1.00
    ELAINE MARIA DE SANT ANNA                     43985238          200716               200801              2.00
    ELAINE MARIA DE SANT ANNA                     43985238          200716               200802              3.00
    ELAINE MARIA DE SANT ANNA                     43985238          200716               200716              0.00
    EURIDES DE BARROS SANTOS                      38146681          200716               200802              0.00
    EURIDES DE BARROS SANTOS                      38146681          200716               200801              0.00
    EURIDES DE BARROS SANTOS                      38146681          200716               200716              0.00
    EURIDES DE BARROS SANTOS                      38146681          200716               200717              0.00
    JOSEFA DA SILVA RIBEIRO DE AVILA              34589813          200716               200801              0.00
    JOSEFA DA SILVA RIBEIRO DE AVILA              34589813          200716               200717              1.00
    JOSEFA DA SILVA RIBEIRO DE AVILA              34589813          200716               200716              0.00
    JOSEFA DA SILVA RIBEIRO DE AVILA              34589813          200716               200802              1.00
    KARLA RESENDE MARANHAO                        42536502          200716               200801              0.00
    KARLA RESENDE MARANHAO                        42536502          200716               200802              0.00
    KARLA RESENDE MARANHAO                        42536502          200716               200717              1.00
    KARLA RESENDE MARANHAO                        42536502          200716               200716              0.00
    DC_NOME_CONSULTORA                       CD_CONSULTORA NM_CICLO_INICIO NM_CICLO_OPERACIONAL      VL_INDICADOR
    MARISTELA MATIAS DE ALIXANDRIA                 4488954          200716               200716              0.00
    MARISTELA MATIAS DE ALIXANDRIA                 4488954          200716               200717              1.00
    MARISTELA MATIAS DE ALIXANDRIA                 4488954          200716               200801              2.00
    MARISTELA MATIAS DE ALIXANDRIA                 4488954          200716               200802              0.00
    24 rows selectedthanks
    Message was edited by:
    muttleychess

    If I treat your question right (not sure) you want to have separate counts for some specific conditions within one group.
    Maybe CASE is that you need:
    SQL> select deptno, job from emp order by 1,2;
        DEPTNO JOB
            10 CLERK
            10 MANAGER
            10 PRESIDENT
            20 ANALYST
            20 ANALYST
            20 CLERK
            20 CLERK
            20 MANAGER
            30 CLERK
            30 MANAGER
            30 SALESMAN
            30 SALESMAN
            30 SALESMAN
            30 SALESMAN
    14 rows selected.
    SQL> select deptno, count(case job when 'CLERK' then 1 end) "clerks",
      2  count(case job when 'SALESMAN' then 1 end) "sales"
      3  from emp
      4  group by deptno;
        DEPTNO     clerks      sales
            30          1          4
            20          2          0
            10          1          0Rgds.

  • Get count per each group using t-sql

    Hi All, I have a table with 5 columns and my source data looks like this...
    ID    Doctor     NurseType    VisitID      Date      
    1      Sam       Main-Nurse      10        09/23/2013
    1      Tom       Sub-Nurse       10        09/23/2013
    1                   Sub-Nurse       10        09/23/2013
    2      Ryan      Sub-Nurse       24        10/29/2013
    2      Ron       Main-Nurse      24        10/29/2013
    3                    Main-Nurse      35        04/12/2014
    3                    Main-Nurse      35        04/12/2014
    3                    Sub-Nurse       35        04/12/2014
    3                     Main-Nurse      40        05/12/2014
    3       Greg       Main-Nurse      40        05/12/2014
    3                     Sub-Nurse       40        05/12/2014
    4       susan     Main-Nurse       45        06/12/2014
    4       Roby       Main-Nurse      45        06/12/2014
    4                     Sub-Nurse       45        06/12/2014
    I want output to be in this format. I want number of doctors present in each ID group per each date using t-sql.
    Output:
    ID      Comments      VisitID      Date
     1       2 doctors       10        09/23/2013
     2       2 doctors       24        10/29/2013
     3       0 doctor        35        04/12/2014       
     3       1 doctor        40        05/12/2014
     4       1 doctor        45        06/12/2014
    Note:
    1)NurseType column always will have Main-Nurse and sub-nurse values.Each ID group will have minimum one main and sub-nurses.
    2) In the above sample date , Id=3 repeated 2 times becoz visitID and date is different.
    3) Also in ID=4(records), even though we have 2 doctors susan and roby we consider them as one doctor becoz NurseType is same(main-nurse).
    4) Values in the comments field will always be 2 doctors , 1 doctor and 0 doctor. Rules for populating this column
      a) In a ID group if Main-Nurse and sub-nurse has nay doctors then will show as 2 doctors.
      b) In a ID group if Main-Nurse or sub-nurse (any one) has doctor then will show as 1 doctor.
      c) In a ID group if Main-Nurse and sub-nurse both doesn't have any doctors then will show as 0 doctor
    Create statement:
    Create table sample  ( ID Int null ,Doctor varchar(25) null,NurseType varchar(20) null ,VisitID int null,Date datetime null)
    Insert statement:
    Insert into sample (ID,Doctor,NurseType,VisitID,Date) values  (1,'Sam,Main-Nurse' ,  10 ,  '09/23/2013')
    Insert into sample (ID,Doctor,NurseType,VisitID,Date) values  (1,'Tom,Sub-Nurse'  ,  10 , '09/23/2013')
    Insert into sample (ID,Doctor,NurseType,VisitID,Date) values  (1, ,'Sub-Nurse'  ,  10 , '09/23/2013')
    Insert into sample (ID,Doctor,NurseType,VisitID,Date) values  (2,'Ryan','Sub-Nurse'   , 24 ,10/29/2013')
    Insert into sample (ID,Doctor,NurseType,VisitID,Date) values  (2,'Ron' , 'Main-Nurse' ,     24,'10/29/2013')
    Insert into sample (ID,Doctor,NurseType,VisitID,Date) values  (3,  , 'Main-Nurse' ,     35  ,'04/12/2014')
    Insert into sample (ID,Doctor,NurseType,VisitID,Date) values  (3,  ,  'Main-Nurse' ,     35 ,'04/12/2014')
    Insert into sample (ID,Doctor,NurseType,VisitID,Date) values  (3, ,  'Sub-Nurse' ,      35 ,'04/12/2014')
    Insert into sample (ID,Doctor,NurseType,VisitID,Date) values  (3,  ,  Main-Nurse',      40  ,'05/12/2014')
    Insert into sample (ID,Doctor,NurseType,VisitID,Date) values  (3,'Greg', 'Main-Nurse',      40 ,'05/12/2014')
    Insert into sample (ID,Doctor,NurseType,VisitID,Date) values  (3,  ,  'Sub-Nurse' ,      40,'05/12/2014')
    Insert into sample (ID,Doctor,NurseType,VisitID,Date) values  (4, 'susan' ,  'Main-Nurse' ,      45,'06/12/2014')
    Insert into sample (ID,Doctor,NurseType,VisitID,Date) values  (4, 'Roby' ,  'Main-Nurse' ,      45,'06/12/2014')
    Insert into sample (ID,Doctor,NurseType,VisitID,Date) values  (4,  ,  'sub-Nurse' ,      45,'06/12/2014')
    Thanks.
    sql

    I had to correct the sample script a bit. The query you are asking for comes after the inserts.
    Create table sample ( ID Int null ,Doctor varchar(25) null,NurseType varchar(20) null ,VisitID int null,Date datetime null)
    Insert into sample (ID,Doctor,NurseType,VisitID,Date) values (1,'Sam','Main-Nurse' , 10 , '09/23/2013')
    Insert into sample (ID,Doctor,NurseType,VisitID,Date) values (1,'Tom','Sub-Nurse' , 10 , '09/23/2013')
    Insert into sample (ID,Doctor,NurseType,VisitID,Date) values (1, NULL,'Sub-Nurse' , 10 , '09/23/2013')
    Insert into sample (ID,Doctor,NurseType,VisitID,Date) values (2,'Ryan','Sub-Nurse' , 24 ,'10/29/2013')
    Insert into sample (ID,Doctor,NurseType,VisitID,Date) values (2,'Ron' , 'Main-Nurse' , 24,'10/29/2013')
    Insert into sample (ID,Doctor,NurseType,VisitID,Date) values (3, NULL, 'Main-Nurse' , 35 ,'04/12/2014')
    Insert into sample (ID,Doctor,NurseType,VisitID,Date) values (3, NULL, 'Main-Nurse' , 35 ,'04/12/2014')
    Insert into sample (ID,Doctor,NurseType,VisitID,Date) values (3, NULL, 'Sub-Nurse' , 35 ,'04/12/2014')
    Insert into sample (ID,Doctor,NurseType,VisitID,Date) values (3, NULL, 'Main-Nurse', 40 ,'05/12/2014')
    Insert into sample (ID,Doctor,NurseType,VisitID,Date) values (3,'Greg', 'Main-Nurse', 40 ,'05/12/2014')
    Insert into sample (ID,Doctor,NurseType,VisitID,Date) values (3, NULL , 'Sub-Nurse' , 40,'05/12/2014')
    go
    SELECT ID, COUNT(Doctor) DoctorCnt, VisitID, Date
    FROM sample
    GROUP BY ID, VisitID, Date
    go
    DROP TABLE sample
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Counting across views & comparing

    I have several views all of which have the following structure:
    id number
    value number
    Now in a loop, I have the names of all the views I'm interested in. From the list of those views, I do a count grouping by the id as:
    select id,count(id) from myview group by id;
    This will give me a list like:
    id count
    100 3
    200 1
    Now, I need to do a similar count in the second view and all the other views from my list. Upto this point its ok .But now, I need to sum up the similar values obtained from these views. For example in the second view if I got the following result:
    id count
    100 1
    300 1
    Then my final result should look like:
    id count
    100 4
    200 1
    300 1
    Thats not enough.
    After storing these final values somewhere, I need to compare each of these individual counts with the results obtained from a similar query on another table
    by each id.
    Any help will be greatly appreciated.

    Thanks for the first part. But, it doesn't fit my requirement because I am getting the view name one by one in a loop and I can't do the union all at a time. I guess what I need is an array or a PL/SQL table to hold the values in each subsequent count and then keep on adding the values to the array. Then ultimately I need to compare the values in the array with the values I obtain from executing a query against a table. This will be like:
    If the values in the array are:
    myarray(id,count)
    with the values(100,4) (200,1),(300,1)
    Then I execute a query against a database table as:
    select id, count(id) from mydatabasetable group by id;
    Then I should be able to compare the values in the array/PL/SQL table with the results obtained by this query.For example: how many 100s, 200s.. are there in the array against how many 100s, 200s.. are there in the database table. I hope the problem is understandable now.

Maybe you are looking for

  • Apple Color won't preview clips properly and Motion crashes on startup. Do I need a new video card?

    I have a 2009 8-core Mac Pro (2.26Ghz) with a GT120 graphics card. I use Final Cut Studio 3 frequently, and up until recently without any hitches. Last week, Color started previewing clips as black with touches of red (I'm assuming a readout of the c

  • Best Practice loading Dimension Table with Surrogate Keys for Levels

    Hi Experts, how would you load an Oracle dimension table with a hierarchy of at least 5 levels with surrogate keys in each level and a unique dimension key for the dimension table. With OWB it is an integrated feature to use surrogate keys in every l

  • Auto-upgraded to itunes 6.0.5 - crashes ever since

    I auto-upgraded to itunes 6.0.5 - crashes ever since. I have - corrected preferences, restarted, closed all other programs, restarted. Tried to re-install itunes with fresh copy downloaded from your site. On re-installation dialogue box says the thre

  • Apple TV, Airplay, & iPads in our classrooms.

    We have 70 Apple TV's, with names and passwords, on our campus.  Both teachers and students have iPads.  Since the iOS 8 updates we are having issues with the list of Apple TV's showing in the Airplay list.  It is also very difficult to find the corr

  • Left speaker drops out randomly in iTunes 7

    First problem I have had with iTunes. After installing v7 my left speaker randomly drops out. Stopping/starting the song again or going to a new song clears it up... but it randomly happens over and over. Any ideas? Thanks.