TSQL query to calculate Count / Sum grouping by date on a Pivot Table

Hi All
I need help to group the pivot table output to group by dates and sum/count the values. I have a table like shown below.
Date
Student 
Subject
Hunt
Marks
18/02/2014
Sam 
Maths
1
20
18/02/2014
Sam 
Maths
1
10
18/02/2014
Sam 
Maths
2
30
18/02/2014
Luke
Science
1
50
17/02/2014
Sam 
Maths
2
50
17/02/2014
Luke
Science
2
60
16/02/2014
Luke
Science
2
20
16/02/2014
Luke
Science
3
20
I want to Group by dates and move the Hunt to columns calculating their counts and sum their marks too. Like given below.
I wrote a pivot query like below but If i group it with dates and calculate the total marks it throws aggregate errors.
Create Table Student_Log ([Date] datetime ,Student varchar (20), Subject varchar (20) ,Hunt int ,Marks int )
Go
INSERT INTO Student_Log ([Date],Student, [Subject],Hunt,Marks) VALUES('2014-02-18 15:00:00.000','Sam ','Maths','1','20')
INSERT INTO Student_Log ([Date],Student, [Subject],Hunt,Marks) VALUES('2014-02-18 15:00:00.000','Sam ','Maths','1','10')
INSERT INTO Student_Log ([Date],Student, [Subject],Hunt,Marks) VALUES('2014-02-18 15:00:00.000','Sam ','Maths','2','30')
INSERT INTO Student_Log ([Date],Student, [Subject],Hunt,Marks) VALUES('2014-02-18 15:00:00.000','Luke','Science','1','50')
INSERT INTO Student_Log ([Date],Student, [Subject],Hunt,Marks) VALUES('2014-02-17 15:00:00.000','Sam ','Maths','2','50')
INSERT INTO Student_Log ([Date],Student, [Subject],Hunt,Marks) VALUES('2014-02-17 15:00:00.000','Luke','Science','2','60')
INSERT INTO Student_Log ([Date],Student, [Subject],Hunt,Marks) VALUES('2014-02-16 15:00:00.000','Luke','Science','2','20')
INSERT INTO Student_Log ([Date],Student, [Subject],Hunt,Marks) VALUES('2014-02-16 15:00:00.000','Luke','Science','3','20')
Go
select * from Student_Log
select [DATE] , [Student], [Subject] ,[1],[2],[3],[4],Total =([1]+[2]+[3]+[4])
from
( select [Date], [Student], [Subject],[Hunt],[Marks] from Student_Log
)x
pivot
count ( [Hunt]) for [Hunt]
in ([1],[2],[3],[4])
)p
order by [Date] desc
I have done this far only. More than this I need to enhance it with the Percentage of Hunts for each Student.
ie like below table.
On 18th Sam in Maths he had 2 rows on 1st hunt  and 1 row on 2nd hunt. So On the Pivot table is it possible to represent it on percentage using the Total Attempts column.
Thanks a lot in advance.
Its runnung in SQL 2000 Server.

Create Table Student_Log ([Date] datetime ,Student varchar (20), Subject varchar (20) ,Hunt int ,Marks int )
Go
INSERT INTO Student_Log ([Date],Student, [Subject],Hunt,Marks) VALUES('2014-02-18 15:00:00.000','Sam ','Maths','1','20')
INSERT INTO Student_Log ([Date],Student, [Subject],Hunt,Marks) VALUES('2014-02-18 15:00:00.000','Sam ','Maths','1','10')
INSERT INTO Student_Log ([Date],Student, [Subject],Hunt,Marks) VALUES('2014-02-18 15:00:00.000','Sam ','Maths','2','30')
INSERT INTO Student_Log ([Date],Student, [Subject],Hunt,Marks) VALUES('2014-02-18 15:00:00.000','Luke','Science','1','50')
INSERT INTO Student_Log ([Date],Student, [Subject],Hunt,Marks) VALUES('2014-02-17 15:00:00.000','Sam ','Maths','2','50')
INSERT INTO Student_Log ([Date],Student, [Subject],Hunt,Marks) VALUES('2014-02-17 15:00:00.000','Luke','Science','2','60')
INSERT INTO Student_Log ([Date],Student, [Subject],Hunt,Marks) VALUES('2014-02-16 15:00:00.000','Luke','Science','2','20')
INSERT INTO Student_Log ([Date],Student, [Subject],Hunt,Marks) VALUES('2014-02-16 15:00:00.000','Luke','Science','3','20')
Go
select * from Student_Log
;with mycte as
Select [Date], [Student], [Subject] ,
Count(CASE WHEN [Hunt]=1 Then Hunt End) as Hunt1,
Count(CASE WHEN [Hunt]=2 Then Hunt End) as Hunt2,
Count(CASE WHEN [Hunt]=3 Then Hunt End) as Hunt3,
Count(CASE WHEN [Hunt]=4 Then Hunt End) as Hunt4,
Count(CASE WHEN [Hunt]=1 Then Hunt End)
+Count(CASE WHEN [Hunt]=2 Then Hunt End)
+Count(CASE WHEN [Hunt]=3 Then Hunt End)+
+Count(CASE WHEN [Hunt]=4 Then Hunt End) as Total,
ISNULL(SUM(CASE WHEN [Hunt]=1 Then Marks End),0) as Mark1,
ISNULL(SUM(CASE WHEN [Hunt]=2 Then Marks End),0) as Mark2,
ISNULL(SUM(CASE WHEN [Hunt]=3 Then Marks End),0) as Mark3,
ISNULL(SUM(CASE WHEN [Hunt]=4 Then Marks End),0) as Mark4
from Student_Log
Group By [Date], [Student], [Subject]
Select [Date], [Student], [Subject]
, Cast(Hunt1*1./Total*100 as int) as [1]
, Cast(Hunt2*1./Total*100 as int) as [2]
,Cast(Hunt3*1./Total*100 as int) as [3]
,Cast(Hunt4*1./Total*100 as int) as [4]
,Total,Marks=( Mark1+Mark2+Mark3+Mark4)
from mycte
order by [Date] DESC, Student desc
drop table Student_Log

Similar Messages

  • MSSQL Query/View Single Line Output For Combined Multiple Data Elements - Possible Pivot Table?

    HELLO...
    I hope you experts out there can help me.  Consider the following (2) Tables in MSSQL:
    1. TENDERED --> Primary Key = DATE / DOC_NO / PAYMENT_SEQ_NO
    DATE
    DOC_NO
    PMNT_SEQ_NO
    PAYCODE_TYPE
    AMOUNT
    2. TENDERED_CR_CARD -->Primary Key = DATE / DOC_NO / PAYMENT_SEQ_NO
    DATE
    DOC_NO
    PMNT_SEQ_NO
    CR_CARD_NO_MASKED
    CR_CARD_NAME
    CR_CARD_EXP_DATE
    These two tables are certainly related, based on their Primary Key values.
    Now, consider the following data in those two tables:
    DATE            
    DOC_NO      PMNT_SEQ_NO              
    PAYCODE_TYPE               
    AMOUNT
    03/10/2014         100001 
    1             
    CASH            
    100.00
    03/10/2014         100001 
    2             
    CASH                             
    -9.75
    03/10/2014         100002 
    1             
    CASH                             
    50.00
    03/10/2014         100002 
    2             
    VISA                             
    100.00
    03/10/2014         100002 
    3             
    VISA             
                   250.00
    03/10/2014         100003 
    1             
                            MC
    125.00
    03/10/2014         100003 
    2             
    AMEX           
    75.00
    DATE          
    DOC_NO PMNT_SEQ_NO  CR_CARD_MASKED     
    NAME            
    CR_CARD_EXP
    03/10/2014  100002   2                       4225******801289  
    MARY JONES   2016/08/31
    03/10/2014  100002   3                       4121******637442  
    JOHN DOE      2015/04/30
    03/10/2014  100003   1                       5428******971134  
    MIKE BAKER   2018/09/30
    03/10/2014  100003   2                       3732*****344756    
    LINDA LIU      2017/07/31
    OK...so what we NEED...is a Combined, SINGLE RECORD Audit Report type query. 
    The resulting query should show, based on the Data from above, the SINGLE LINE represented in the Attached Spreadsheet. 
    NOTE...what's important to point out here..is that ONLY the 'CASH' Tender gets "summed"...EACH INDIVIDUAL Credit Card record MUST have its own Field...as represented in the corresponding Columns of the Spreadsheet (i.e. PMT_TYP_1, AMT_1, PMT_TYP_2,
    AMT_2, and so forth).
    PLEASE HELP!  Any suggestions/advice would be most appreciated! 
    Thank You!...Mark

    I would not do this in SQL if I could possibly avoid it.  Instead do it in the front end.
    If you must do it in SQL, this is a dynamic pivot on multiple columns.  Naomi Nosonovsky has a blog at
    http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/dynamic-pivot-on-multiple-columns/ on how to do that.  Look especially at her second example using the claims table.  Of course, you must do some manipulation even before you do the multi-column
    pivot, since you must first combine all the cash entries.
    So one way to do it would be to build a temp table with all the entries you have except the cash entries combined into one payment sequence number.  To do that you may need specifications that are not clear to me from what you have given us.  For
    example, if PMT SEQ 1 is VISA,  PMT SEQ 2 is CASH, PMT SEQ 3 is VISA, PMT SEQ 4 is CASH, and PMT SEQ 5 is VISA, you want to combine the two cash payments.  So they become PMT SEQ 2?  If so, what happens to PMT SEQ 4 - is it left N/A or does
    PMT SEQ 5 become PMT SEQ 4?
    But once you have this temp table with the cash payments combined in the algorithm you need, then you can use Naomi's method to do the multi-column pivot.  Note that Naomi uses the code
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_Name = 'Claims'
    to get the column names from the permanent table Claims.  To get the column names from a temp table use code like the following.  To find the column names in a temp table named #MyTempTable, do
    From tempdb.sys.columns
    Where object_id = OBJECT_ID('#MyTempTable')
    But as I say, if feasible, I would do this in the front end, not in SQL.  T-SQL is a very good language for storing and retrieving data, not so good at formatting it. 
    Tom

  • How to calculate New customers and Returning customers in a Pivot Table?

    Hi,
    I have a Pivot table with columns as Order Date, Customer Name, Qty, Cost, Freight, Invoice, Adv Payment. I have only 30 customers and 11000 transactions for 4 years sales period.
    How to calculate New customers and Returning customers in Pivot Table for any given Month or Quarter or Year. I am open to use helper column, formula or a calculated field etc
    Thanks
    Arjun

    Hi Arjun,
    I have received the file and read it, based on your further explain, I know your requested more clarity. In my view, the requested could be done via VBA code or Select function in other dataset, like Access/SQL. (Because before we count the new
    customer and return customer, we might to filter them via rule, the formula need to assign the customer one by one. So, it's inefficient)
    Thus, I recommend we try the above workaround: Use macro or Select function in Access. If you have further question about the coding, please post to the MSDN forum for Excel
    http://social.msdn.microsoft.com/Forums/en-US/home?forum=exceldev&filter=alltypes&sort=lastpostdesc
    The reason why we recommend posting appropriately is you will get the most qualified pool of respondents, and other partners who read the forums regularly can either share their knowledge or learn from your interaction with us. Thank you for your understanding.
    George Zhao
    TechNet Community Support
    It's recommended to download and install
    Configuration Analyzer Tool (OffCAT), which is developed by Microsoft Support teams. Once the tool is installed, you can run it at any time to scan for hundreds of known issues in Office
    programs.

  • How to calculate value from perticular column and row in pivot table

    Hi all,
    I am having following pivot table.
    Country
    A
    B
    C
    D
    F
    G
    H
    J
    K
    L
    M
    Grand Total
    Canada
    1
    1
    3
    3
    12
    14
    13
    97
    China
    8
    4
    3
    19
    India
    2
    47
    448
    176
    395
    3656
    1964
    1360
    8077
    USA
    1545
    352
    380
    26
    10
    4
    8
    32
    2054
    1023
    758
    4624
    UK
    12
    19
    13
    23
    33
    298
    Grand Total
    1545
    352
    381
    29
    72
    474
    184
    427
    5743
    3028
    2167
    13114
    Now I want sum of Columns A, B, C, K, M where Country = India in one field.
    and sum of D, F, g in another field. and sum of remainig columns in another field.
    How can i get sum of values with some where condition in pivot table.
    Thanks,

    Hi Michael,
    Following is the representation which i want
    CouRntry
    ROW LABLES
    A
    B
    C
    Total of
    ABC
    F
    G
    Total
    Of FG
    J
    K
    L
    TOTAL
    of JL
    Grand
    Total
    Canada
    1
    1
    3
    3
    12
    14
    13
    97
    China
    8
    4
    3
    19
    India
    2
    47
    448
    176
    395
    3656
    1964
    1360
    8077
    USA
    1545
    352
    380
    26
    10
    4
    8
    32
    2054
    1023
    758
    4624
    UK
    12
    19
    13
    23
    33
    298
    Grand Total
    1545
    352
    381
    29
    72
    474
    184
    427
    5743
    3028
    2167
    1
    Also if i get sum how can i add a column in between of the fields.
    Thanks

  • Percentage of Total Count of Category in Raw Data Column in Pivot Table

    I have normalized my data in Excel and I have a column: "question 1" and then a column for "gender" which has values as "female" and "male". I have created a pivot table for these two variables, "Gender" and
    "Question 1". My values for Females and Males from the Gender data are presented within my pivot table. I want to present these numbers as percentages of Total "Females" and "Males" that are in the "Gender" column in
    my master dataset. Pivot tables will only allow me to do %'s of data already in the pivot table
    I am attempting to use Calculated Fields within Pivot Tables to resolve this. I do not want to create a separate column in my master data set, but rather, complete all calculations within the pivot table

    Thank you very much, 
    The steps you provided use the total "gender" within the pivot table as the "grand total". 
    If I have a binomial variable, "gender" with "male" as one of the variables, I need the grand total be the total male in the raw data. 
    Example: if there are 100 total males in the raw data for the column "gender"
    and I construct a pivot table with a dependent variable which is a survey question and "gender"  and 30 males "agreed" with the survey question and 20 females "agreed" with the survey question, your instructions for % of grand total would show 60% for
    males who agree [males + females who replied to the survey question],
    when, what I need is the total males in the raw data, 100, used as the total so that the percentage of males who answered "agreed" to the survey question is 30% of all males. 
    Thank you very much

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

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

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

  • Query to find the sum of different groups of same column

    Hi ,
    I have a table as follows:
    customers
    custid credit amt month
    001 C 2000 Jan-2012
    001 D 5000 Feb-2012
    001 C 3000 Mar-2012
    001 C 3000 Apr-2012
    001 D 7000 May-2012
    I Have to write a single query to calculate the sum of credit and sum of debit value separately.
    Thanks & Regards,
    SB2011

    Hi,
    SB2011 wrote:
    Hi ,
    I have a table as follows:
    customers
    custid credit amt month
    001 C 2000 Jan-2012
    001 D 5000 Feb-2012
    001 C 3000 Mar-2012
    001 C 3000 Apr-2012
    001 D 7000 May-2012
    I Have to write a single query to calculate the sum of credit and sum of debit value separately.Getting the sum sounds like a job for the SUM function.
    Getting separate sums for credit and debit sounds like a job for GROUP BY.
    Thanks & Regards,
    SB2011Here's one way:
    SELECT    credit
    ,       SUM (amt)     AS total
    FROM       customers
    GROUP BY  credit
    I hope this answers your question.
    If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only), and the results you want from that data.
    Explain, using specific examples, how you get those results from that data.
    Always say what version of Oracle you're using (e.g. 11.2.0.2.0).
    See the forum FAQ {message:id=9360002}

  • How to calculate counts from different dates into 1 date

    Hi,
    I have a scenario below
    ID
    Type
    Country
    Date
    123AP1
    P
    US
    1/1/2009
    123A1
    A
    WO
    4/4/2010
    123A2
    A
    US
    6/6/2011
    123A3
    A
    US
    8/8/2011
    So, the logic I need to display is -
    If, Type = P AND Country=US then count 1 where ID has 123AP1
    else If Type = A AND Country=US then count 1 more where ID has 123AP1 on date 1/1/2009 (i.e. on Type P date)
    So, result should show
    ID
    Type
    Country
    Date
    Count
    123AP1
    P
    US
    1/1/2009
    3
    123A1
    A
    WO
    4/4/2010
    0
    123A2
    A
    US
    6/6/2011
    123A3
    A
    US
    8/8/2011

    Please simplify the question while asking to make it easy to understand.. this question is very confusing to understand..
    For your purpose you should be able to get the result using calculation context based count on a  conditional variable with all your logic
    Create a variable like below
    var =if  [Type] = 'P' [ID] = '123AP1' and [Country] = 'US' then 1 else if Type] = 'A' [ID] = '123A1' and [Country] <> 'US'  thenn 1
    And then create a formula on this variable like below
    Count = sum([Var]) forall [Date]

  • What will be the peoplesoft query to calculate voluntary termination count and involuntary termination count? I am working on OBIA HR analytics workforce deployment reports and need to validate the reports

    what will be the peoplesoft query to calculate voluntary termination count and involuntary termination count? I am working on OBIA HR analytics workforce deployment reports and need to validate the reports. I also want to know the tables involved

    Hi Andrew,
    Part A:
    I've done some restating of the question, and distributed the calculations among several fields, not all of which need to be included on the visible layout. Other than formatting the Date fields and moving the 'Completed Date' field and its label, I've left this in the default "Layout 1" produced by AppleWorks.
    Field List:
    Priority: Popup menu with six items: 00, J, D, 1, 2, 3  Defaults to 00
    TL (time limit in months): Calculation:  CHOOSE('Priority',0,1,3,4,6,12)
    Received: Date. Option: Automatically insert today's date (ie. Date Record created) (may be edited)
    Target Date: Calculation:
    DATE(YEAR('Received')+INT(MONTH('Received')+'TL')/12,MOD(MONTH('Received')+'TL', 12),DAY('Received'))
    Remaining (Days): Calculation: INT('Target Date'+1-NOW())  (see revision below)
    Completed: Checkbox. Set default value to Unchecked.
    Completed Date: Date: Entered manually
    OnTarget: Calculation: IF('Completed',IF('Completed Date'<'Target Date',"On Target","Over"),IF(INT(NOW())>'Target Date',"Over","On Target"))
    The On Target field shows the current status of the case while still open, and the state on the closing date when it was closed.
    Having done that, I was unhappy with the Remaining field continuing to calculate an ever larger negative number after the case had been closed. Hence this revision below:
    Remaining: Calculation: IF('Completed','Target Date'-'Completed Date',INT('Target Date'+1-NOW()))
    Shows the number of days remaining while the case is open, the days remaining at completion if the case has been marked Completed and the completion date entered.
    Rsults (and some further formatting of the Layout) below.
    Part B:
    You will need Subsummary parts when sorted on Completed and on On Target. Fields can appear on  a Layout only once, so each subsummary part will need a separate Summary type field for each field to be summarized.
    Regards,
    Barry

  • COUNT with Group By clause issue

    Good Morning everyone. I have a simple query that calculates the count of 3 expressions. It is supposed to group by region and province as a result set, but instead places the TOTAL count for each expression in the region and province fields. What am I doing wrong? This is my query:
    SELECT TABLE1."Province",
    TABLE1."Region",
    (SELECT(COUNT(TABLE1."Nationality"))
    FROM TABLE1
    WHERE (TABLE1."Nationality" <> 'United States'
    AND TABLE1."Nationality" <> 'Nat1')
    OR (TABLE1."Medical" <> 'ON MEDICAL'
    AND TABLE1."Region" <> 'CONUS')
    ) "TCN COUNT",
    (SELECT(COUNT(TABLE1."Nationality"))
    FROM TABLE1
    WHERE (TABLE1."Nationality" = 'United States')
    OR (TABLE1."Medical" <> 'ON MEDICAL'
    AND TABLE1."Region" <> 'CONUS')
    ) "US COUNT",
    (SELECT(COUNT(TABLE1."Nationality"))
    FROM TABLE1
    WHERE (TABLE1."Nationality" = 'Nat1')
    OR (TABLE1."Medical" <> 'ON MEDICAL'
    AND TABLE1."Region" <> 'CONUS')
    ) "HCN COUNT"
    FROM TABLE1
    GROUP BY TABLE1."Province",
    TABLE1."Region";
    Any help would be appreciated. Thank you.
    Aqua

    Because you are not passing any values to the inner query from the outer one..
    Are you looking for this?
    SELECT      TABLE1."Province",
         TABLE1."Region",
         sum (
           case when (
                 TABLE1."Nationality" != 'United States'
                 AND TABLE1."Nationality" !=  'Nat1'
                OR (
                TABLE1."Medical" != 'ON MEDICAL'
                AND TABLE1."Region" != 'CONUS'
                 ) then 1 else 0 end
             ) "TCN COUNT",
         sum (
           case when (
                TABLE1."Nationality" = 'United States'
                OR (
                TABLE1."Medical" 'ON MEDICAL'
                AND TABLE1."Region" 'CONUS'
                   ) then 1 else 0 end
             ) "US COUNT",
         sum (
           case when (
                TABLE1."Nationality" = 'Nat1'
                  OR (
                   TABLE1."Medical" 'ON MEDICAL'
                   AND TABLE1."Region" 'CONUS'
                     ) then 1 else 0 end
             ) "HCN COUNT"
    FROM TABLE1
    GROUP BY TABLE1."Province",TABLE1."Region";

  • Count / sum function in report problem

    Hi
    In my report i was using this code to output the area code and count the man_suspend records from the Trans_code colum. Like so
    SELECT AUN_CODE,
    COUNT(*) FROM rr_transaction WHERE trans_code = 'MAN_SUSPEND'
    GROUP BY AUN_CODE
    AUN_CODE      COUNT(*)
    201                   1
    202                   1
    204                   3But it wasnt outputing the zeros so i tried using the follwoing statements:
    select aun_code,sum(case when rr_transaction.trans_code = 'MAN_SUSPEND' then 1 else 0 end)
    from rr_transaction
    group by aun_code
    SELECT AUN_CODE,
    count(case when trans_code = 'MAN_SUSPEND' then 1 end)
    FROM rr_transaction
    GROUP BY AUN_CODE
    These two statements do give me the desire output
    of :
    AUN_CODE      COUNT(*)
    200                   0
    201                   1
    202                   1
    204                   3etc
    But when i try using these select statments in my data model in Oracle reports it creates the query box with a broken data link icon and wont let me join it to other queries (the aun_code is the primary key)
    Im abit stumped why it will work the first select statement but not the other two!??

    Much nicer than my paltry attempt.
    select iv2.object_type,nvl(object_count,0) object_count
      from
    SELECT object_type,
                COUNT(object_id) object_count 
      FROM user_objects
    WHERE object_type  in ('TABLE' ,'FUNCTION','INDEX','PACKAGE')
    GROUP BY object_type
    ) iv1
    (select distinct object_type
                  from user_objects) iv2
               where iv2.object_type = iv1.object_type(+)

  • Calculate count of zero (key figures)

    Hi Friends,
    The output of the query is as follows:
    Row
    Group
    Sub group
    Column
    No. of incidents
    Processing time
    Characteristics are placed in row and keyfigures in column. There is an additional characteristice "team" which is not displayed in the report.
    Now i wish to count the number of incidents for which the processing time is zero and also with the restriction of team A and team B.
    I am able to count the number incidents with processing time zero. But able to restrict this to particular team.
    Regards,
    Surjit

    What I meant to ask is, time is recorded by name level right?
    If one team can have 5 different names and out of those 5 names, 3 of them have time as ZERO and 2 of them dont have time ZERO. When you set the exceptiona aggregation, you will get 3 because calcualtion is done at name level, but you can not perform the exception aggregation at team level because that will be performed on the summation of all the times from all 5 persons of that team, which will not be ZERO.
    My same question was, if you have 3 teams under sub group, how do you want to see the number in the report.
    Row1 Row2 Row3 Col1 Col2
    Grp  Sub Grp  Team1 x  x
    ____________Team2 x x
    This is not possible without having team in the report. Either you sum them up, but the team level calcualtion it self is wrong, so it really doesnt matter if you add them up at sub group level or not.
    - Danny

  • 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

  • Extend existing tsql query to get all customers, even if they have no instances of the previous query - thought this would be easy, but...

    Hi all,
    The previous query is absolutely ok.
    The only thing i want to change is ...
    get all the previous available ve1 AND NEW: if a AGNR has no ve1-instance, regardless get an ve1-instance with the agnr filled but f.e. the other fields empty
    The grouping could made in reporting-logic later, and not in the tsql-query.
    resultset i need:
    - all agnr, if the have an ve1-instance or not
    Groups (hierarchy) i need, later in Report:
    - AGNR
       - ve1 (with all the left joind fields pg, vnfk, vnpk, vm (if they are)
       - if a agnr has no instance of ve1 --> print: "NO ver available"
    SELECT
    ve1.new_verid,
    ve1.new_no,
    ve1.statuscode,
    ve1.statuscodename,
    ve1.createdon,
    ve1.createdby,
    ve1.createdbyname,
    ve1.new_begin,
    DATEPART(yyyy, ve1.new_begin) AS begin_year,
    ve1.new_end,
    ve1.new_vn_fid,
    ve1.new_vn_fidname,
    ve1.new_vn_kid,
    ve1.new_vn_kidname,
    vnpk.new_how_old,
    ve1.new_vg,
    ve1.new_vgname,
    ve1.new_vs,
    ve1.new_vsname,
    ve1.new_vstat,
    ve1.new_vstatname,
    ve1.new_zw,
    ve1.new_zwname,
    ve1.new_bn_zw,
    ve1.new_rlz_v,
    ve1.new_pgid,
    ve1.new_pgidname,
    pg.accountnumber as pg_accountno,
    ve1.new_agnr_agnr_avmid,
    ve1.new_agnr_agnr_avmidname,
    AGNR.new_vm_kid AS vm_contactid,
    AGNR.new_vm_kidname AS vm_contactidname,
    ve1.new_efv,
    ve1.new_efvname,
    CASE
    WHEN ve1.new_vn_kid IS NOT NULL THEN 'Private Customer'
    WHEN ve1.new_vn_fid IS NOT NULL THEN 'Account Customer'
    ELSE 'Kunde'
    END AS kunde_typ,
    DATEPART(yyyy, vnpk.birthdate) as vnpk_birth_year,
    CASE
    WHEN ((ve1.new_rlz_v IS NOT NULL) OR (ve1.new_rlz_v > 0))
    THEN ve1.new_rlz_v
    WHEN (DATEPART(yyyy, ve1.new_begin) IS NOT NULL) AND (DATEPART(yyyy, vnpk.birthdate) IS NOT NULL)
    THEN 65 - ((DATEPART(yyyy, ve1.new_begin)) - (DATEPART(yyyy, vnpk.birthdate)))
    ELSE 20
    END AS vlz_calc,
    CASE
    WHEN ((ve1.new_bnj IS NOT NULL) OR (ve1.new_bnj > 0)) THEN ve1.new_bnj
    WHEN ((ve1.new_bn_zw IS NOT NULL) OR (ve1.new_bn_zw > 0))
    THEN
    CASE
    WHEN new_zw = '100000008' THEN ve1.new_bn_zw * 12
    WHEN new_zw = '100000004' THEN ve1.new_bn_zw * 4
    WHEN new_zw = '100000002' THEN ve1.new_bn_zw * 2
    WHEN new_zw = '100000001' THEN ve1.new_bn_zw * 1
    WHEN new_zw = '100000006' THEN ve1.new_bn_zw
    ELSE 0
    END
    ELSE 0
    END AS bnj_calc
    FROM
    Filterednew_ver AS ve1
    LEFT OUTER JOIN Filterednew_agnr AS AGNR
    ON ve1.new_agnr_agnr_avmid = AGNR.new_agnrid
    LEFT OUTER JOIN FilteredAccount AS pg
    ON ve1.new_pgid = pg.accountid
    LEFT OUTER JOIN FilteredAccount AS vnfk
    ON ve1.new_vn_fid = vnfk.accountid
    LEFT OUTER JOIN FilteredContact AS vnpk
    ON ve1.new_vn_kid = vnpk.contactid
    LEFT OUTER JOIN FilteredContact AS vm
    ON AGNR.new_vm_kid = vm.contactid
    WHERE
    (ve1.createdon >= @Begin_Week)
    AND (ve1.createdon <= @End_Week)
    AND (ve1.new_vg = @vg)
    AND (ve1.statuscode = '1')
    AND (ve1.new_efv <> '100000000' OR ve1.new_efv IS NULL)
    AND (ve1.new_vstat <> '100000004' OR ve1.new_vstat IS NULL)
    AND (ve1.new_zw IN ('100000008','100000004','100000002','100000001','100000006'))
    ORDER BY
    ve1.createdon
    i thought, and tried with right joins, but i think i need to change the sight (the complete query)?
    thx for all kind of help
    Greets Peb

    Hi Peb,
    Please provide sample data and expected results.

  • How to tune the query..."sum" operation is taking too much long time...

    how to reduce the execution time for the below query..."sum" operation is taking too much long time....
    SELECT
    B.DP_AVPS_STATUS,
    SUM(DP_AD_CURR_BAL*D.ISIN_CLOSE_PRICE) Qty,
    B.DP_NET_WORTH,
    B.CMN_DP_FLAG,
    B.RESTRAIN_TYPE ,
    B.LETT_GENR_DATE,
    E.MAX_NET_WORTH,
    E.MIN_NET_WORTH
    FROM DPMADV0 A, PABRNCHDTLP0 B, PABANKCCYP0 D,PADPNETWORTHDTLP0 E,
    (SELECT CID_NUMB FROM CFCUSTMASTD0
    WHERE SUB_TYPE NOT IN (1,2,5,6,7,28,29,30,31,40,41,48,49,50,57,83)) C
    WHERE A.DP_AD_BR_NBR = B.BRNCH_NUMB
    AND A.DP_AD_CCY_CDE = D.CCY_ALPHA_CODE
    AND A.DP_AD_ACCT_NBR = C.CID_NUMB
    AND E.DP_ACCOUNT_TYPE = B.DP_ACCOUNT_TYPE
    AND SUBSTR(B.BRNCH_NUMB,1,3) like SUBSTR(:hvBrnchNumb,1,3)
    AND ((B.DP_TYPE IN (2) AND B.DP_ACCOUNT_TYPE IN (10, 11)) or
    (B.DP_TYPE IN (3) and B.DP_ACCOUNT_TYPE=11 ) )
    AND B.DEL_FLAG = 'N'
    AND B.DP_STATUS = 'A'
    AND D.ISIN_STATUS = 'A'
    GROUP BY B.DP_NET_WORTH,B.RESTRAIN_TYPE,B.DP_AVPS_STATUS,E.MAX_NET_WORTH,
    E.MIN_NET_WORTH,B.CMN_DP_FLAG,B.LETT_GENR_DATE;

    Hi,
    please produce a plan with rowsource statistics (if not sure how, follow instructions in http://savvinov.com/2012/09/24/a-sqlplus-script-for-diagnosing-poor-sql-plans/) and post it using tags to preserve formatting.
    Best regards,
      Nikolay
    P.S. I also suggest that you work on your open threads:
    Handle:      946903 
    Status Level:      Newbie
    Registered:      Jul 16, 2012
    Total Posts:      11
    Total Questions:      5 (5 unresolved)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

Maybe you are looking for

  • Bi7.0 to portal integration using template installer

    hi frnds, i change my connectivity step to bi to ep 7.0 now i m using template installer for full bi installation all the step are successfully completd. when i am cheking with java based Note 937697 - Usage of SAP NetWeaver BI Diagnostics & Support

  • Why does AT&T treat prospective customers badly?

    We had problems with AT&T when we lived at our previous home. So we tried Comcast this time but their service is bad too. Uverse is now available at our new address. But AT&T is like an octopus with tentacles that do not work with each other! On 6/27

  • MP3 or video files are playing instead of downloading

    when iam downloading the videos or mp3 files it starts playing insread of downloading

  • Search engine hijacked by Yahoo in Safari Mountain Lion?

    I installed Mountain Lion these past days and since then, my Safari browser is hijacked by Yahoo, although I did set Google as my default search engine, and even changed DNS to google (8.8.8.8 and 8.8.4.4). I am at a loss - what is happening?  Help?

  • Send EFTs to bank

    Hi All, Our client wants to enhance Automated Payment program and wants to send Electronic Fund Transfers using Idocs/EDI,We are already sending EFTs using Idocs/EDI to the same bank from a different client in our business and wants to replicate the