Aggregate rows with count and add fraction of whole result set sum

Here's the explaination by example
# Source table
ID | TYPE
1 | A
2 | A
3 | B
4 | C
5 | C
6 | A
7 | C
8 | A
Now, I'm aggregating and counting:
TYPE | count(*)
A | 4
B | 1
C | 3
I need to assign to row also an information about the fraction of overall sum of rows, so simply divide each count by 8 (in that case), so the result is:
TYPE | frac
A | 0.5
B | 0.125
C | 0.375
Is it possible to do this in NOT nested query, using some Oracle function?
Edited by: Wojtus-J on Feb 18, 2011 5:47 AM

Why can you not use a subquery?
SQL> with test_data as
  2      (
  3      select 'A' x from dual union all
  4      select 'A' x from dual union all
  5      select 'B' x from dual union all
  6      select 'C' x from dual union all
  7      select 'C' x from dual union all
  8      select 'A' x from dual union all
  9      select 'C' x from dual union all
10      select 'A' x from dual
11      )
12  select
13      x,
14      ratio_to_report(count(*)) over (partition by null)
15  from
16      test_data
17  group by
18      x;
X RATIO_TO_REPORT(COUNT(*))OVER(PARTITIONBYNULL)
A                                             .5
B                                           .125
C                                           .375
SQL>

Similar Messages

  • Help with count and sum query

    Hi I am using oracle 10g. Trying to aggregate duplicate count records. I have so far:
    SELECT 'ST' LEDGER,
    CASE
    WHEN c.Category = 'E' THEN 'Headcount Exempt'
    ELSE 'Headcount Non-Exempt'
    END
    ACCOUNTS,
    CASE WHEN a.COMPANY = 'ZEE' THEN 'OH' ELSE 'NA' END MARKET,
    'MARCH_12' AS PERIOD,
    COUNT (a.empl_id) head_count
    FROM essbase.employee_pubinfo a
    LEFT OUTER JOIN MMS_DIST_COPY b
    ON a.cost_ctr = TRIM (b.bu)
    INNER JOIN MMS_GL_PAY_GROUPS c
    ON a.pay_group = c.group_code
    WHERE a.employee_status IN ('A', 'L', 'P', 'S')
    AND FISCAL_YEAR = '2012'
    AND FISCAL_MONTH = 'MARCH'
    GROUP BY a.company,
    b.district,
    a.cost_ctr,
    c.category,
    a.fiscal_month,
    a.fiscal_year;
    which gives me same rows with different head_counts. I am trying to combine the same rows as a total (one record). Do I use a subquery?

    Hi,
    Whenever you have a problem, please post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) from all tables involved.
    Also post the results you want from that data, and an explanation of how you get those results from that data, with specific examples.
    user610131 wrote:
    ... which gives me same rows with different head_counts.If they have different head_counts, then the rows are not the same.
    I am trying to combine the same rows as a total (one record). Do I use a subquery?Maybe. It's more likely that you need a different GROUP BY clause, since the GROUP BY clause determines how many rows of output there will be. I'll be able to say more after you post the sample data, results, and explanation.
    You may want both a sub-query and a different GROUP BY clause. For example:
    WITH    got_group_by_columns     AS
         SELECT  a.empl_id
         ,     CASE
                        WHEN  c.category = 'E'
                  THEN  'Headcount Exempt'
                        ELSE  'Headcount Non-Exempt'
                END          AS accounts
         ,       CASE
                        WHEN a.company = 'ZEE'
                        THEN 'OH'
                        ELSE 'NA'
                END          AS market
         FROM              essbase.employee_pubinfo a
         LEFT OUTER JOIN  mms_dist_copy             b  ON   a.cost_ctr     = TRIM (b.bu)
         INNER JOIN       mms_gl_pay_groups        c  ON   a.pay_group      = c.group_code
         WHERE     a.employee_status     IN ('A', 'L', 'P', 'S')
         AND        fiscal_year           = '2012'
         AND        fiscal_month          = 'MARCH'
    SELECT    'ST'               AS ledger
    ,       accounts
    ,       market
    ,       'MARCH_12'          AS period
    ,       COUNT (empl_id)       AS head_count
    FROM       got_group_by_columns
    GROUP BY  accounts
    ,            market
    ;But that's just a wild guess.
    You said you wanted "Help with count and sum". I see the COUNT, but what do you want with SUM? No doubt this will be clearer after you post the sample data and results.
    Edited by: Frank Kulash on Apr 4, 2012 5:31 PM

  • "select count(*)" and "select single *" returns different result

    Good day!
    product version SAP ECC 6.0
    oracle10
    data transfers from external oracle db into customer tables using direct oracle db link
    sometimes I get case with different results from 2 statements
    *mytable has 10 rows
    *1st statement
    data: cnt type I value 0.
    select count( * ) into cnt from mytable WHERE myfield_0 = 123 and myfield_1 = '123'.
    *cnt returns 10 - correct
    *2nd statement
    select single * from  mytable WHERE myfield_0 = 123 and myfield_1 = '123'.
    *sy-dbcnt returns 0
    *sy-subrc returns 4 - incorrect, 10 rows are "invisible"
    but
    1. se16 shows correct row number
    2. I update just one row from "invisible" rows using se16 and 2nd statement returns correct result after that
    can not understand why
    thank you in advance.

    Thank you, Vishal
    but,
    general problem is that
    1. both statements have the same WHERE conditions
    2. 1st return resultset with data (sy-dbcnt=10), 2nd return empty dataset, but must return 1 in sy-dbcnt
    Yes, different meaning, you are right, but must 2nd must return 1, because of "select single *" construction, not 0.
    Dataset to process is the same, WHERE conditions are equal...
    I think the problem is that how ABAP interperets select count(*) and "select single *".
    Maybe "select count (*)" scans only PK from index page(s)? and "select single *" scans data pages? and something is wrong with that?
    I'm new in SAP and didn't find any SAP tool to trace dump of data and indexes pages with Native SQL.
    se16 shows all records.
    And why after simple manual update of just one record using se16 "select single *" returns 1?
    I've just marked one row to update, didn't change any data, then pressed "save".

  • Rev. 80: Error with counter and analytic privilege

    Hey guys,
    I have the following structure in my model:
    Attribute View (AT) --> Calculation View 1 (CV1) --> Calculation View 2 (CV2)
    The calculation views only contain the default aggregation. Additionally CV1 has a counter on one of the columns.
    The content is about analyzing roles from ERP.
    AT has columns RIAExtractID (its a GUID), AGR_NAME (Name of the composite role), CHILD_AGR (Name of the single role).
    CV1 has the same columns but also a counter on CHILD_AGR called "NumberofAssignedSingleRoles".
    CV2 has all columns of CV1 but not CHILD_AGR.
    Here is how it looked like in Rev72: (filtered for one AGR_NAME = AC280-RECHERCHE-REPORTS)
    AT:
    CV1:
    CV2:
    (I would not need CV2 to get this result (I could just select these 3 columns from CV1). However, in CV2 the Column NumberofAssignedSingleRoles is of type "attribute" whereas in CV1 it's a "measure", and with this "hardcoded" aggregation in CV2 I can then apply a filter on NumberofAssignedSingleRoles in an OData request giving me for example all roles which have less than 5 single roles assigned. Otherwise you can't filter on a measure.)
    However, now with Rev. 80 the result of CV2 looks like this:
    Although, AT and CV1 still look the same (and return 4 rows with each a different CHILD_AGR). No matter how many child roles have been in CV1, CV2 gives me NumberofAssignedSingleRoles = 1 for every AGR_NAME!
    Trying to track the issue down, I found that using SYSTEM user gives me correct output of NumberofAssignedSingleRoles = 4.
    Since one major difference between my user for testing and SYSTEM are analytic privileges.
    Currently there is a restriction in the analytic privilege for AT: RIAExtractID = 001CC4F....
    When I remove this restriction, the output is correct, too. (i.e. 4 rows in AT, 4 rows in CV1, Counter= 4 in CV2)
    When I add the restriction again, the output is wrong. (i.e. 4 rows in AT, 4 rows in CV1, Counter = 1 in CV2)
    I'm pretty sure this is a bug in SP8/Rev 80.
    What other options do I have to "debug" any further?
    By the way it makes no difference if I move the restriction from AT to CV1 or CV2, behavior is still the same (=wrong).
    Hope you can help me since this is a major problem for my application!
    Kind Regards,
    Fabian

    I cannot believe it. Rev. 91 and still the same Problem.
    @SAP: Do you just don't care or are you not able to reproduce? I could provide small Delivery Unit with Schema, Table, AT and CVs as well as an analytic privilege.

  • Difference of last 2 Rows with Start and End Time

    Hi all,
      This question is an extention to the below question
    http://social.msdn.microsoft.com/Forums/en-US/ca938faf-49a7-4212-afd2-19046cbfcc8b/difference-of-last-2-rows?forum=transactsql
    I got the difference of last 2 rows from the above question. But now the table added with one field StartTime. The final table is
    CREATE TABLE MeterReading
    ReadingID int,
    MeterID int,
    DataCounter int,
    StartTime datetime,
    Value numeric(16,4)
    As per the my first thread i got the best answer like below
    SELECT MeterID, SUM(CASE WHEN Recency = 1 THEN Value ELSE -Value END)
    FROM (
    select DISTINCT MeterID, Value, DENSE_RANK() OVER (PARTITION BY MeterID ORDER BY StartTime DESC) 'Recency'
    from MeterReading
    ) x
    WHERE Recency IN (1,2)
    GROUP BY MeterID
    Now i need to add StartTime to the result. The expectation is, it will take the difference of last and second last record. So i need the starttime as secondlast record starttime and endtime as last record startime. Please help me

    I got a solution like below
    SELECT
    y.ProcessParameterID
    ,MIN(y.StartTime) StartTime
    ,MAX(y.EndTime) EndTime
    ,SUM(y.Value) Value
    FROM
    SELECT
    ProcessParameterID
    ,(CASE WHEN Recency = 2 THEN StartTime ELSE null END) StartTime
    ,(CASE WHEN Recency = 1 THEN StartTime ELSE null END) EndTime
    , SUM(CASE WHEN Recency = 1 THEN Value ELSE -Value END) Value
    FROM (
    select DISTINCT ProcessParameterID, StartTime, Value, DENSE_RANK() OVER (PARTITION BY ProcessParameterID ORDER BY StartTime DESC) 'Recency'
    from LT_LAEMI_HWT_Readings
    ) x
    WHERE Recency IN (1,2)
    GROUP BY ProcessParameterID
    , Recency
    , StartTime
    ) y
    GROUP BY ProcessParameterID
    Can you advice me, is this the correct way or any alternative short method

  • Some problems with af:table (new rows with presetting and autosubmit)

    Hi, I'm working with an af:table, but I'm having some troubles.
    Background:
    Jdev 11.1.1.5.0
    Firefox 6.0.2
    In the Bounded Task flow:
    ExecuteWithParams -> fragment < commit/rollback
    ExecuteWithParams: Set a bind variable with a value from bpm payload for get only rows with that value.
    In the fragment:
    An af:table with a button CreateInsert (the new rows need to use the value of the payload in the hidden column, i don't know how do this, assign the value to the #{row.bindings.IdDistribution.inputValue}) [First problem]
    The inputText of the af:table has the autoSubmit in true. The first time that I fill the cells I got this error in each entered value, after press the tab key.
    ADF-FACES- 60097... ADF_FACES-60096:Server Exception during PPR, #n (where n is 1,2,3,4 for each cell). [Second problem]
    When I press the Commit Button, all values from cells dissapears. And I got the message from validator that cells can't be null. [Third problem]
    If I fill cells again, all work right. Validations, no errors ADF_FACES-60096 and a successful commit.
    How I can solve these problems?
    Thanks in advance.

    Hi,
    you need to bind the value property of the selectOneRadio to the row variable. Say the button updates an attribute "q1" then the value property should point to #{row.bindings.q1.inputValue} assuming you use ADF and ADF BC. The question svary I assume., so you need to query thequestion for each row. For this reference a managed bean doe the f:selectItems and in the managed bean use the #{row} attribute to get a hold of the current rendered row (instance of JUCtrlHierNodeBinding if ADF is used. This has a method getRow() to obtain the Row object). The list then returns the answers to select from
    Frank

  • SQL Server SUM of Multiple rows with where and group by

    I have a table Transaction that looks something like the following :
    TransactionID          
    Currency        
    Credit             
    Debit
    1                                USD                   
    500               0
    2                                Afcu                    
    6000             0
    3                                INR                     
    0                   200
    4                                Pfc                      
    7000             0
    5                                AUD                     
    0                  200
    6                                INR                     
    7000              0
    7                                USD                    
    1000              0
    I write query like this
    select SUM(credit)-SUM(Debit)as [Balance] ,Source from Transaction group by Source
    and it came like
    Balance
    Source           
    1500                        USD
    6000                        Afcu
    6800                        INR
    7000                        Pfc
    -200                         AUD
    But I also want to add  Afcu , Pfc with
    USD and  want output like
    Balance
    Source           
    14500                        USD
    6800                          INR
    -200                           AUD
    Any Idea?

    Here is how you can do it, but you 
    DECLARE @TransTable TABLE
    (TransactionID INT IDENTITY(1,1),
    Currency varchar(10),
    Credit DECIMAL,
    Debit DECIMAL)
    INSERT INTO @TransTable VALUES
    ('USD',500,0),('Afcu',6000,0),('INR',0,200),('Pfc',7000,0),('AUD',0,200),
    ('INR',7000,0),('USD',1000,0)
    SELECT Currency, SUM(credit)-SUM(Debit)as [Balance]
    FROM @TransTable
    WHERE Currency NOT IN ('Afcu', 'pfc','USD')
    GROUP BY Currency
    UNION
    SELECT 'USD', SUM(credit)-SUM(Debit)as [Balance]
    FROM @TransTable
    WHERE Currency IN ('Afcu', 'pfc','USD')
    SQL fiddler example
    Output:
    Hope this will help
    Glad to help! Please remember to accept the answer if you found it helpful. It will be useful for future readers having same issue.
    My Profile on Microsoft ASP.NET forum

  • "cacheHostInfo is null" and Add-SPDistributedCacheServiceInstance : Object reference not set to an instance of an object.

    I am working on a standalone install Sharepoint 2013 (no Active Directory). I found newsfeed feature is not available and checked Distributed Cache service is stopped. When start it “cacheHostInfo is null” is returned.
    I checked the Windows service “AppFabric caching service” is stopped because the default identity “Network Service” not work. Then I change the AppFabric service identity to use “.\administrator” (which is also the sp farm administrator) and the service can
    be started.
    However the “cacheHostInfo is null” when try to start Distributed Cache service in central admin.
    I searched on web and found this blog: http://rakatechblog.wordpress.com/2013/02/04/sharepoint-2013-spdistributedcacheserviceinstance-cachehostinfo-is-null/
    I tried to run the script but it return error:
    Add-SPDistributedCacheServiceInstance : Object reference not set to an
    instance of an object.
    At C:\root\ps\test.ps1:8 char:13
    + $whatever = Add-SPDistributedCacheServiceInstance
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : InvalidData: (Microsoft.Share…ServiceInstance:
    SPCmdletAddDist…ServiceInstance) [Add-SPDistributedCacheServiceInstance]
    , NullReferenceException
    + FullyQualifiedErrorId : Microsoft.SharePoint.PowerShell.SPCmdletAddDistr
    ibutedCacheServiceInstance
    I am not sure what went wrong. Please give me some idea? Thank you for any comment!

    Can you deploy Active Directory as installing without is not a supported installation scenario - http://support.microsoft.com/kb/2764086.
    Trevor Seward
    Follow or contact me at...
    &nbsp&nbsp
    This post is my own opinion and does not necessarily reflect the opinion or view of Microsoft, its employees, or other MVPs.

  • How to Add extra data in result set of cfquerry?

    hi all,
    I am new to cold fusion please help me
    i am using the cfquery tag for executing a select query and getting the system name and system is from that........
    But i want an extra system name and system id to add to the result of that query with out changing the data base ..............
    please any one suggest me ...........IT's URGENT
    Thanks in advance
    Sudheer

    You'll have to use an array and the function queryAddColumn. An example follows.
    Suppose I have a result set called myQuery. There are 5 rows in it. I wish to add 2 new columns to the query, on the fly. The column names are username(type varchar) and userID(type integer)
    <!--- Create array corresponding to column username--->
    <cfset usernameArray = ArrayNew(1)>
    <cfset usernameArray[1] = "[email protected]">
    <cfset usernameArray[2] = "[email protected]">
    <cfset usernameArray[3] = "[email protected]">
    <cfset usernameArray[4] = "[email protected]">
    <cfset usernameArray[5] = "[email protected]">
    <!---
    The next line adds the new column, username, to the query. That's it. Done.
    The array indices correspond to the row numbers in the query.
    The function queryAddColumn returns the column number for the newly added column
    (in case you'll need it, which you usually wont ).
    --->
    <cfset columnNumber = queryAddColumn(myQuery, "username", "VarChar", usernameArray)>
    <!--- Now, do the same for the next new column, userID  --->
    <cfset userIDArray = ArrayNew(1)>
    <cfset userIDArray[1] = "23">
    <cfset userIDArray[2] = "121">
    <cfset userIDArray[3] = "9">
    <cfset userIDArray[4] = "76">
    <cfset userIDArray[5] = "44">
    <cfset columnNumber = queryAddColumn(myQuery, "userID", "integer", userIDArray)>

  • Setting the max and min bounds of a result set

    I'm trying to set the upper and lower bound values of a result set. Meaning, I want to limit the values in my result set to not be below/above a certain number, BUT I want any number in my result set that is below/above the lower/upper bound that i have designated to be decoded to the lower/upper bound number that I have designated. Here's an example to help clarify:
    WITH temp_table AS
    SELECT 1231.12 AS col FROM dual UNION ALL
    SELECT 1001.00 FROM dual UNION ALL
    SELECT -32.0 FROM dual UNION ALL
    SELECT -3.0 FROM dual UNION ALL
    SELECT 332.0 FROM dual UNION ALL
    SELECT 211.0 FROM dual
    SELECT CASE WHEN col < 0 -- 0 is the lower bound
                THEN
                     0
                WHEN col > 1000 -- 1000 is the upper bound
                THEN
                     1000
                ELSE
                     col
           END as desired_result
    FROM   temp_tabledesired result set:
            DESIRED_RESULT
         1000
         1000     
            0
         0
         332
         211I was wondering if there was another function or method of achieving my desired result set without having to use a CASE statement? I have to do this to several columns, and it doesn't seem very efficient to throw a CASE statement around each one.

    LEAST and GREATEST will do that too :
    SQL> WITH temp_table AS
      2  (
      3   SELECT 1231.12 AS col FROM dual UNION ALL
      4   SELECT 1001.00 FROM dual UNION ALL
      5   SELECT -32.0 FROM dual UNION ALL
      6   SELECT -3.0 FROM dual UNION ALL
      7   SELECT 332.0 FROM dual UNION ALL
      8   SELECT 211.0 FROM dual
      9   )
    10  SELECT least(greatest(col, 0), 1000)
    11  FROM temp_table
    12  ;
    LEAST(GREATEST(COL,0),1000)
                           1000
                           1000
                              0
                              0
                            332
                            211
    6 rows selected
    I have to do this to several columns, and it doesn't seem very efficient to throw a CASE statement around each one.Any test case showing CASE as not efficient?
    Edited by: odie_63 on 25 juil. 2012 23:20

  • SQL Server 2012: Import and Export Wizard - Exporting Multiple Result Sets at Once?

    I'm working in SQL Server 2012 trying to export some data from our database into an Excel file. My SQL statement has two separate Select statements. They are not joined by a union. When I Execute them inside of SQL Server Management Studio, with Results
    set to go to a Grid, I get two result sets back. Two full tables of data.
    However, when I use the Import and Export Wizard, the Excel sheet only has the first set of data.
    What do I need to do to have it so both result sets show up in the excel file?

    Why cant use merge them using union/union all if intention is to get them to same sheet? Is it like the metadata is different so that they cant be merged to single sheet?
    If that being the case you need to do it in two steps. 
    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

  • How to - extract query result set in CSV and make multiple files if result set is huge.

    I have a query which returns millions of rows. I need to extract those rows in CSV files. Having said that i want to keep these files under a limit of 500 MB . Result set can be distributed among multiples files but each file can not be > 500 MB in size.
    How to achieve this?

    You may use this standard! procedure from Blushadow and produce something useful for your need. https://community.oracle.com/message/6499123#6499123

  • Alv add new row with counter

    Hello.
    I would like to add a new row to an ALV GRID CONTROL in which one of the fields is a counter. Which methods, codes have I to change/write?
    For example:
    ALV
    COUNTER FLIGHT DESTINATION
    1     1234  CDG
    2     3443  SVQ
    On adding a new row :
    COUNTER FLIGHT DESTINATION
    1     1234  CDG
    2     3443  SVQ
    3
    Thanks in advance!!!

    There are two options.
    1.  Use the data_changed event to put in the values.
    - Enable edit mode for the grid, so the row create/insert/copy icons appear on the toolbar. 
    - Create an event handler for the DATA_CHANGED event
    - In this method, use attribute table er_data_changed->MT_INSERTED_ROWS to check for new rows, and then er_data_changed->modify_cell to put in the line number.
    The problem is that if your counter field is set as non-editable, then you cannot put a value in...
    2.  implement your own add function.
    - Add a button to the toolbar (implement methiod for event handle_toolbar)
    - Create an event handler for event handle_user_command.
    - In the handler method, add a row to the outtab table used by the grid (with the correct line number).
    - CALL METHOD gr_grid->refresh_table_display to update the display with the additional line.
    Regards
    Michael

  • Collect file count and add to CSV file.

    I have this script efficiently crafted by Jacques Rioux and I now what to do a little more with it.
    What it currently does is look on my desktop at a select number of Folders on my desktop. It then looks at the keyword information and then returns the results to a csv file.
    it looks for all the photographs; shot by Matthew. edited by Matthew etc.... with the date appended to the start and then the next time the script is run it adds the next data to the bottom of the last.
    The result looks like this
    19/12/2012,255,412,37,68
    27/12/2012,197,342,16,26
    From the fist line you can see on the 19th December 2012 I shot 255 images
    No what I would like it to do is:-
    a) Specifaically look in the folders of the desktop whose name begins with BH, BU, DA, DI, DO, FR, IN, NO, MA, TM, WA, PR, SE (These folders may or may not exist at the time, but are the only folders it should look at)
    b) also do a file count of the contents of the above individual folders and append it to the csv file. Again a folder may not exist. Where it doesn't exist the file count must = 0 so that it can then be added to the CSV file.
    This is how I hope the line to look like from the CSV file,
    19/12/2012,255,412,37,68, 5,3,20,25,60,101,25,0,85,5,40,0,0
    from the line above you can see that the folders NO, PR, and SE were all non existant and therefore a 0 was written in its place on the CSV file.
    Below is the working script that looks for the keywords.
    set spotlightqueryList to {"Shot by Matthew", "Editted by Matthew", "Shot by Shah", "Editted by Shah"}
    set thefolders to {"Desktop"}
    set thekind to "PSD"
    set csvFileName to "ProductivityLog.csv"
    set tHome to path to home folder as string
    set tc to count spotlightqueryList
    set theseCount to {}
    repeat tc times
              set end of theseCount to 0
    end repeat
    repeat with i in thefolders
              set thepath to my existsItem(tHome & i)
              if thepath is not "" then -- exists
                        repeat with j from 1 to tc
                                  set tQuery to item j of spotlightqueryList
                                  do shell script "mdfind -onlyin " & thepath & " " & tQuery & " " & thekind & " | wc -l" -- wc return the number of lines
                                  set item j of theseCount to (item j of theseCount) + (the result as integer) -- add the number of lines
                        end repeat
              end if
    end repeat
    set csvPath to "DCKGEN:Brands:Zoom:Online Photography:" & csvFileName
    set oTID to text item delimiters
    set text item delimiters to "," -- CSV delimiter
    set thisLine to (theseCount as text) -- convert list to text, each number is separated by comma
    set text item delimiters to oTID
    tell (current date) to set tDate to short date string
    set beginning of theseCount to tDate -- insert the date (first column)
    set csvPath to "DCKGEN:Brands:Zoom:Online Photography:" & csvFileName
    set oTID to text item delimiters
    set text item delimiters to "," -- CSV delimiter
    set thisLine to (theseCount as text) -- convert list to text, each number is separated by comma
    set text item delimiters to oTID
    --- append this line to CSV file
    do shell script "echo " & (quoted form of thisLine) & " >>" & quoted form of POSIX path of csvPath
    on existsItem(f)
              try
                        return quoted form of POSIX path of (f as alias) -- exists
              end try
              return "" -- else not exists
    end existsItem
    (* just a way to visually see it working
    set dialog to "Matt Shot: \"" & item 1 of theseCount & "\"" & return & return & "Matt Edit: \"" & item 2 of theseCount & "\"" & return & return & "Shah Shot: \"" & item 3 of theseCount & "\"" & return & return & "Shah Edit: \"" & item 4 of theseCount & "\"" & return & return
    display dialog dialog
    This is what I began to wrote but really have no idea how I would write it into the data into the CSV file and also I was struggling to get the non existant folder to = 0?
    tell application "Finder"
              set folderA to (get first folder of desktop whose name starts with "BH")
              set folderB to (get first folder of desktop whose name starts with "Bu")
              set folderC to (get first folder of desktop whose name starts with "Da")
              set folderD to (get first folder of desktop whose name starts with "DI")
              set folderE to (get first folder of desktop whose name starts with "Do")
              set folderF to (get first folder of desktop whose name starts with "Fr")
              set folderG to (get first folder of desktop whose name starts with "In")
              set folderH to (get first folder of desktop whose name starts with "Ma")
              if (exists (get first folder of desktop whose name starts with "No")) is true then
                        set folderI to (get first folder of desktop whose name starts with "No")
              else
                        set folderI to "0"
                        set folderJ to (get first folder of desktop whose name starts with "To")
                        set folderK to (get first folder of desktop whose name starts with "Wa")
                        if (exists (get first folder of desktop whose name starts with "SE")) is truethen
                                  set folderL to (get first folder of desktop whose name starts with"SE")
                        else
                                  set folderL to "0"
                                  if (exists (get first folder of desktop whose name starts with "PR"))is true then
                                            set folderM to (get first folder of desktop whose name starts with "PR")
                                  else
                                            set folderM to "0"
                                            set folderM to (get first folder of desktop whose name starts with "PR")
                                  end if
                        end if
              end if
              tell application "System Events"
                        set contentsA to (number of files in folderA)
                        set contentsB to (number of files in folderB)
                        set contentsC to (number of files in folderC)
                        set contentsD to (number of files in folderD)
                        set contentsE to (number of files in folderE)
                        set contentsF to (number of files in folderF)
                        set contentsG to (number of files in folderG)
                        set contentsH to (number of files in folderH)
                        set contentsI to (number of files in folderI)
                        set contentsJ to (number of files in folderJ)
                        set contentsK to (number of files in folderK)
                        set contentsL to (number of files in folderL)
                        set contentsM to (number of files in folderM)
              end tell
    end tell
    I hope someone can help me compile the remaining data.
    Many thanks
    Matt

    OK i've done my homework and I have been able to get a lot closer I just need to make the search specific to a number of folders on the desktop?
    Line 7 explains how I would like it to search.
    set spotlightqueryList to {"Shot_by_Matthew", "Editted_by_Matthew", "Shot_by_Shah", "Editted_by_Shah"}
    set spotlightqueryList2 to {"AL70", "BH70", "BH70", "BU40", "ES20", "DV25", "DJ30", "RA30", "FR10", "GT55", "MA65", "MB65", "MC65", "FI65", "MF65", "MH65", "NN_", "TM15", "WA35", "PR_", "SE_"}
    set thefolders to {"Desktop"}
    --Here I need to limit the search so that it only looks in folders of the desktop whose name begins with "BH", "BU", "DA", "DI", "DO", "FR", "IN", "MA", "NO", "TM", "WA", "PR", "SE"
    set thekind to "PSD"
    set csvFileName to "ProductivityLog.csv"
    set tHome to path to home folder as string
    set tc to count spotlightqueryList
    set theseCount to {}
    repeat tc times
              set end of theseCount to 0
    end repeat
    set tc2 to count spotlightqueryList2
    set theseCount2 to {}
    repeat tc2 times
              set end of theseCount2 to 0
    end repeat
    repeat with i in thefolders
              set thepath to my existsItem(tHome & i)
              if thepath is not "" then -- exists
                        repeat with j from 1 to tc
                                  set tQuery to item j of spotlightqueryList
                                  do shell script "mdfind -onlyin " & thepath & " " & tQuery & " " & thekind & " | wc -l" -- wc return the number of lines
                                  set item j of theseCount to (item j of theseCount) + (the result as integer) -- add the number of lines
                        end repeat
              end if
    end repeat
    repeat with i2 in thefolders
              set thepath2 to my existsItem2(tHome & i2)
              if thepath2 is not "" then -- exists
                        repeat with j2 from 1 to tc2
                                  set tQuery2 to item j2 of spotlightqueryList2
                                  do shell script "mdfind -onlyin " & thepath2 & "  -name " & tQuery2 & " " & thekind & " | wc -l" -- wc return the number of lines
                                  set item j2 of theseCount2 to (item j2 of theseCount2) + (the result as integer) -- add the number of lines
                        end repeat
              end if
    end repeat
    set csvPath to "DCKGEN:Brands:Zoom:Online Photography:" & csvFileName
    set oTID to text item delimiters
    set text item delimiters to "," -- CSV delimiter
    set thisLine to (theseCount as text) -- convert list to text, each number is separated by comma
    set thisLine2 to (theseCount2 as text) -- convert list to text, each number is separated by comma
    set text item delimiters to oTID
    tell (current date) to set tDate to short date string
    set beginning of theseCount to tDate -- insert the date (first column)
    set csvPath to "DCKGEN:Brands:Zoom:Online Photography:" & csvFileName
    set oTID to text item delimiters
    set text item delimiters to "," -- CSV delimiter
    set thisLine to (theseCount as text) -- convert list to text, each number is separated by comma
    set thisLine2 to (theseCount2 as text) -- convert list to text, each number is separated by comma
    set text item delimiters to oTID
    --- append this line to CSV file
    do shell script "echo " & (quoted form of thisLine) & (quoted form of thisLine2) & " >>" & quoted form of POSIX path of csvPath
    on existsItem(f)
              try
                        return quoted form of POSIX path of (f as alias) -- exists
              end try
              return "" -- else not exists
    end existsItem
    on existsItem2(f)
              try
                        return quoted form of POSIX path of (f as alias) -- exists
              end try
              return "" -- else not exists
    end existsItem2
    (* just a way to visually see it working
    set dialog to "Matt Shot: \"" & item 1 of theseCount & "\"" & return & return & "Matt Edit: \"" & item 2 of theseCount & "\"" & return & return & "Shah Shot: \"" & item 3 of theseCount & "\"" & return & return & "Shah Edit: \"" & item 4 of theseCount & "\"" & return & return
    display dialog dialog

  • Problems updating panel with remove() and add()

    Hi,
    I have a class which extends JPanel, and everytime I call repaint on it I am trying to add the contents of a Hashtable to the screen. If I do not include the this.removeAll() then it will add those components to the Container...problem is that it will add them everytime so I will have multiple copies of the same thing. If I try and remove them first (notice how I put a boolean in so that I dont remove them before they are added) before adding them (so clear the screen), then they will never appear, no matter where I put the removeAll() or where i put the add(). Same applies for a remove() statement on each individual component.
    I have spent hours on this stupid thing !
    Any ideas would be much appreciated
    Cheers
    Ray
    public void paintComponent(Graphics g) {
         super.paintComponent(g);
         if (painted) {
         this.removeAll();
         globalClock.setRate((int)nodeRef.getAverageRate());
         painted = true;
         //Iterate over the keys in the map
        Iterator keyIt = nodeRef.returnKeyIterator();
        Iterator valIt = nodeRef.returnValueIterator();
       while (keyIt.hasNext()) {
             String key = (String)keyIt.next();
            NodeObject node = (NodeObject)valIt.next();
            nameLabel = new JLabel("Client Name");
            nameField = new JTextField(key);
            currentTimeLabel = new JLabel("CurrentTime");
             currentTimeField = new JTextField(Double.toString(node.getCurrentTime()));
             updateLabel = new JLabel("Update Interval");
             updateField = new JTextField(Integer.toString(node.getInterval())); //default
             speedLabel = new JLabel("Clock Rate");
             speedField = new JTextField(Double.toString(node.getRate()));
             add(currentTimeLabel);
             add(currentTimeField);
             add(updateLabel);
             add(updateField);
             add(speedLabel);
             add(speedField);
            add(nameLabel);
             add(nameField);
        globalRateLabel = new JLabel("Global Speed");
        globalRateField = new JTextField(globalClock.getRate() + " %");
        globalRateField.setEditable(false);
        add(globalRateLabel);
        add(globalRateField);
    }

    Sometimes I will have two things in the hashTable, sometimes I will have one hundred !
    Each time repaint() is called I want this to represent the current status of the Hashtable, so If on one repaint there are 100 pairs in the Hashtable it will add all the details of these pairs to the Container, however on the next repaint if there are only two pairs I dont want the other 98 entries on the page at all. You cant do this with just a component modifier, you have to remove the component completely. I figured that the easiest way to do this would be just to remove all the components completely, and then add what was needed by going through the Hashtable again. (note:effiecency is not a concern)
    And yes I realise repaint() is called on resizes etc etc, but this wont adversely affect the program
    Ray

Maybe you are looking for