SQL query to group data by Code and dates

Hi There,
I have the following table structure
col1 col2 col3
code1 21-jan-2012 tested
code1 20-jan-2012 tested
code1 01-jun-2012 tested
code2 01-jun-2012 tested
code3 04-jun-2012 tested
so on
The output should be some thing like
code Week1 week2 week 3 week4 week5 till about last 14 weeks from the date we are running
code1 1 0 0 0 0
code2 1 0 0 0 0
code 3 0 1 0 0 0
where 1, 0 is actually the counts and not sum and the week in this case, should have maybe been since we are in the second week it should have been
code .....................week3 may week4 may week1 jun week2june
Was looking for suggestions on how to get this done.
I am assuming this would require some sort of a pivot query?
Thanks,
Sun

Hi, Sun,
sun1977 wrote:
Thanks EKH,
Yes, in lines of the output of this query. Is it possible to,
1. In the query, if condition is met, the it simply displays 1 else 0. Basically, we need to get the count of the number of the codes in that week. So if code 1 happened 5 times, it should show 5.Sure; use COUNT instead of MAX.
2. Provide the output between two dates. Lets say, I have to do it for the last 14 weeks from sysdate. Then will the logic of week1 = 1 work?Use date arithmetic to get the number of days between the starting date and col2, then divide by 7 to get the number of weeks. Use that number instead of the value returned by TO_CHAR.
3. any suggestions if the counts have to be changed to percentages. How can we have the percentage value showingYou can do that. Exactly how depends on exactly what you want. It may involve using the analytic RATIO_TO_REPORT function in a sub-query. Post the exact results you want from the sample data that Ekh posted (or new sample data that you post), and explain how you get those results from that data.
4. Would we also be able to add a date bind value. Lets say, if the user selects start date as may, 1st, 2012 and end date as jun5th. It sort of shows the same data but in weekly format for the weeks between the period selected?Sure, just use those values in a WHERE clause. The output needs to have a fixed number of columns, however. Say that number is 14. You can give a range that only covers 5 weeks, but the output will have 9 0's at the end of every row. You can give a range that covers 15 or more weeks, but the weeks after 14 will not be shown. To get around that requires dynamic SQL (if you want each week in a real column) or string aggregation. See {message:id=3527823}
Point 3 is different from point 1 as in, the first one would be maybe using your logic but hardcoding for 14 weeks. Point three would be a little more dynamic.
Thanks for your time.
Sun
Edited by: sun1977 on Jun 7, 2012 2:28 AM
EXEC  :start_dt_txt := '01-May-2012';
EXEC  :end_dt_txt   := '05-Jun-2012';
WITH  got_week_num  AS
     SELECT  col1, col2
     ,     1 + FLOOR ( (col2 - TO_DATE (:start_dt_txt, 'DD-Mon-YYYY'))
                     / 7
                 )     AS week_num
     FROM    t
     WHERE     col2     >= TO_DATE (:start_dt_txt, ':DD-Mon-YYYY')
     AND     col2     <  TO_DATE (:end_dt_txt,   ':DD-Mon-YYYY') + 1
SELECT       col1
,       COUNT (CASE WHEN week_num =  1 THEN 1 END)     AS week_1
,       COUNT (CASE WHEN week_num =  2 THEN 1 END)     AS week_2
,       COUNT (CASE WHEN week_num =  3 THEN 1 END)     AS week_3
,       COUNT (CASE WHEN week_num =  4 THEN 1 END)     AS week_4
,       COUNT (CASE WHEN week_num =  5 THEN 1 END)     AS week_5
,       COUNT (CASE WHEN week_num =  6 THEN 1 END)     AS week_6
,       COUNT (CASE WHEN week_num = 14 THEN 1 END)     AS week_14
FROM       got_week_num
GROUP BY  col1
ORDER BY  col1
;Edited by: Frank Kulash on Jun 7, 2012 5:53 AM

Similar Messages

  • I want to use the SQL query IF EXIST to update or insert data in a ms access table, but it doesn´t work

    Hi,
    I want to use the SQL query IF EXIST to update or insert data in a ms access table, but it doesn´t work
    (fault number -2147217900)
    I want to search for a value in a ms access table , if it exist i want to update it, if not i want to insert a new row.
    Working with LabView 7.1, database con. toolset.
    Who can HELP?
    Thanks a lot
    Marco

    Hello,
    I think that If exist is not a standar SQL command (I know it exists I think in Oracle and SQL server), MS access doesn't support it, so I think the best way to do it is first make a Select and then either an Update or an insert, sorry...
    Paulo

  • SQL Query to get Project Plan Name and Resource Name from Reporting database of Project Server 2007

    Can you please help me to write an SQL Query to get Project Plan Name and Resource Name from Reporting database of Project Server 2007. Thanks!!

    Refer
    http://gallery.technet.microsoft.com/projectserver/Server-20072010-SQL-Get-a99d4bc6
    SELECT
    dbo.MSP_EpmAssignment_UserView.ProjectUID,
    dbo.MSP_EpmAssignment_UserView.TaskUID,
    dbo.MSP_EpmProject_UserView.ProjectName,
    dbo.MSP_EpmTask_UserView.TaskName,
    dbo.MSP_EpmAssignment_UserView.ResourceUID,
    dbo.MSP_EpmResource_UserView.ResourceName,
    dbo.MSP_EpmResource_UserView.ResourceInitials
    INTO #TempTable
    FROM dbo.MSP_EpmAssignment_UserView INNER JOIN
    dbo.MSP_EpmProject_UserView ON dbo.MSP_EpmAssignment_UserView.ProjectUID = dbo.MSP_EpmProject_UserView.ProjectUID INNER JOIN
    dbo.MSP_EpmTask_UserView ON dbo.MSP_EpmAssignment_UserView.TaskUID = dbo.MSP_EpmTask_UserView.TaskUID INNER JOIN
    dbo.MSP_EpmResource_UserView ON dbo.MSP_EpmAssignment_UserView.ResourceUID = dbo.MSP_EpmResource_UserView.ResourceUID
    SELECT
    ProjectUID,
    TaskUID,
    ProjectName,
    TaskName,
    STUFF((
    SELECT ', ' + ResourceInitials
    FROM #TempTable
    WHERE (TaskUID = Results.TaskUID)
    FOR XML PATH (''))
    ,1,2,'') AS ResourceInitialsCombined,
    STUFF((
    SELECT ', ' + ResourceName
    FROM #TempTable
    WHERE (TaskUID = Results.TaskUID)
    FOR XML PATH (''))
    ,1,2,'') AS ResourceNameCombined
    FROM #TempTable Results
    GROUP BY TaskUID,ProjectUID,ProjectName,TaskName
    DROP TABLE #TempTable
    -Prashanth

  • SQL Query (updateable report) Region - Conditionally Hide and Set Values

    SQL Query (updateable report) Region - Conditionally Hide and Set Values
    Outline of requirement :-
    Master / Detail page with Detail updated on same page using SQL Query (updateable report).
    The detail region has the following source
    SELECT item_id,
           contract_id,
           CASE WHEN hardware_id IS NOT NULL THEN
                   'HA'
                WHEN backup_dev_id IS NOT NULL THEN
                   'BD'
                WHEN hardware_os_id IS NOT NULL THEN
                   'HS'
           END item_type,
           hardware_id,
           backup_dev_id,
           hardware_os_id
    FROM   "#OWNER#".support_items
    WHERE  contract_id = :P26_CONTRACT_IDThe table support_items implements arced relationships and has the following columns
    CREATE TABLE SUPPORT_ITEMS
      ITEM_ID         NUMBER                        NOT NULL,
      CONTRACT_ID     NUMBER                        NOT NULL,
      HARDWARE_ID     NUMBER,
      BACKUP_DEV_ID   NUMBER,
      HARDWARE_OS_ID  NUMBER
    )A check type constaint on support_items ensures that only one of the fk's is present.
          (    hardware_id    IS NOT NULL
           AND backup_dev_id  IS NULL
           AND hardware_os_id IS NULL
    OR    (    hardware_id    IS NULL
           AND backup_dev_id  IS NOT NULL
           AND hardware_os_id IS NULL
    OR    (    hardware_id    IS NULL
           AND backup_dev_id  IS NULL
           AND hardware_os_id IS NOT NULL
          )    Hardware_Id is a FK to Hardware_Assets
    Backup_dev_id is a FK to Backup_Devices
    Hardware_os_id is a FK to Hardware_op_systems
    The Tabular Form Element based on item_type column of SQL query is Displayed As Select List (based on LOV) referencing a named list of values which have the following properties
    Display Value     Return Value
    Hardware Asset    HA
    Backup Device     BD
    Computer System   HSThe Tabular Form Elements for the report attributes for hardware_id, backup_dev_id and hardware_os_id are all Displayed As Select List (Based on LOV).
    What I want to do is only display the Select List for the FK depending on the value of the Select List on Item Type, e.g.
    Item_Type is 'HA' then display Select List for hardware_id, do not display and set to NULL the Select Lists for backup_dev_id and hardware_os_id.
    Item_Type is 'BB' then display Select List for backup_dev_id, do not display and set to NULL the Select Lists for hardware_id and hardware_os_id.
    Item_Type is 'HS' then display Select List for hardware_os_id, do not display and set to NULL the Select Lists backup_dev_id and hardware_id.
    There are properties on elements to conditionally display it but how do we reference the values of the SQL query Updateable region? they are not given a page item name?
    Also on the Tabular For Elements there is an Edit tick against a report item - however when you go to the Column Attributes there is not a property with which you can control the Edit setting.
    What's the best way of implementing this requirement in APEX 3.1?
    Thanks.

    >
    Welcome to the forum: please read the FAQ and forum sticky threads (if you haven't done so already), and update your profile with a real handle instead of "user13515136".
    When you have a problem you'll get a faster, more effective response by including as much relevant information as possible upfront. This should include:
    <li>Full APEX version
    <li>Full DB/version/edition/host OS
    <li>Web server architecture (EPG, OHS or APEX listener/host OS)
    <li>Browser(s) and version(s) used
    <li>Theme
    <li>Template(s)
    <li>Region/item type(s) (making particular distinction as to whether a "report" is a standard report, an interactive report, or in fact an "updateable report" (i.e. a tabular form)
    With APEX we're also fortunate to have a great resource in apex.oracle.com where we can reproduce and share problems. Reproducing things there is the best way to troubleshoot most issues, especially those relating to layout and visual formatting. If you expect a detailed answer then it's appropriate for you to take on a significant part of the effort by getting as far as possible with an example of the problem on apex.oracle.com before asking for assistance with specific issues, which we can then see at first hand.
    I have a multi-row region that displays values and allows entries in a number of fields.Provide exact details of how this has been implemented. (An example on apex.oracle.com is always a good way to do this.)
    I should like the fields to be conditional in that they do not permit entry, but still display, if certain conditions apply (e.g. older rows greyed out). Can this be done? Almost anything can be done, often in multiple ways. Which are appropriate may be dependent on a particular implementation, the skills available to implement it, and the effort you're willing to expend on it. Hence it's necessary to provide full details of what you've done so far...

  • ABAP User Roles and Query for accessing particular T- codes and Reports

    dear Gurus
    I have one problem, i want to know about ABAP User Query ,i have one requirement my user wants to Lock all the HR Std versus Customized reports in T- code SQ01,other department peoples also see the Payslips and Hr personal reports which is harmfull to the dept so i want to Lock all the reports in Std T- code in SQ01 and i have created one Customized User Roles or Query in which the T-codes and Reports are assigned only those particular user can access the T-codes and Std reports .how can it be possible i dont have any idea about user roles and Queries .
    kindly help me out or send me some documents related to user roles and queries
    regards ritesh sharma

    Hi Ritesh,
    https://www.sdn.sap.com/irj/scn/go/portal/prtroot/docs/library/uuid/103cafc2-7a64-2b10-14b3-eddb7d324561
    Regards,
    Flavya

  • Data Integration Middleware and Data integration Architect Java Projects

    Hi all,
    What is meant by the terminologies
    Data Integration Middleware and Data integration Architect Java ProjectsAre both of them the same?
    Rony

    Moved to a different forum.

  • What is PMS Data Migration Experience and Data Migration Scripts preparatio

    Hi All what is PMS Data Migration Experience and Data Migration Scripts preparation
    why we use these in HRMS(EBS)

    Pl provide a link to where you got these terms from.
    "PMS Data Migration Experience" is not an EBS term - most likely a vendor or third-party phrase/tool/software.
    "Data Migration" in HRMS (and other EBS modules) typically refers to the process of moving data from a legacy system to EBS during the process of going-live with EBS.
    HTH
    Srini

  • HT1807 in the general setting, i turned off cellular and made sure that the cellular date, enable lte and data roaming was off. if when off, i was receiving telephone calls while travelling in the usa

    while travelling in the usa, i turned off cellular in settings and also made sure that the cellular data, enable lte and data roaming was off. \however, i was still receiging telephone calls

    Turning off cellular data doesn't turn off the ability of the phone to make or receive phone calls. In order to do that, you'd need to put the phone in Airplane Mode.

  • Difference Between Data Services Designer and Data Services Workbench

    Hello All,
    I am new to Data Services .
    What is the difference between Data Services Designer and Data Services Workbench .
    Am bit confused in the above two .
    Please help me to understand the same.
    Thanks in advance.
    Aisurya

    Workbench is used to create, display and modify the objects. It will display the source table data and we can see the logs of the job which we have executed and also we can see the status of a job. In bods 4.2 you can design the dataflow in workbench in previous release we don’t have that option but designer contains debugging option, you can write scripts,  it will support all databases; these option are not available in workbench. for more information refer this document:
    https://decisionfirst.files.wordpress.com/2014/07/data-services-workbench-intro.pdf
    http://scn.sap.com/community/data-services/blog/2014/03/01/data-services-42-workbench
    http://scn.sap.com/community/data-services/blog/2013/01/24/data-services-workbench-part-1

  • Difference between Data carrier type and Data carrier??

    Hi experts,
    Could you please explain me the difference between Data carrier type and Data carrier with an example??
    Regards,
    Kiran T

    hi Kiran,
    Data carrier is to achive communication between server and user front end. We can define one data carrier type along with path as default for all or seperate data carriers type for specific users in define data carrier in SPRO. This defined data carriers again we assign to application in defining network for workstation application in SPRO.
    By using data carrier we can upload to & download originals from server. We can change and print the documents from server.
    Please award pts if its useful / need further information.
    Pramod

  • SQL query using Group by and Aggregate function

    Hi All,
    I need your help in writing an SQL query to achieve the following.
    Scenario:
    I have table with 3 Columns. There are 3 possible values for col3 - Success, Failure & Error.
    Now I need a query which can give me the summary counts for distinct values of col3 for each GROUP BY of col1 and col2 values. When there are no values for col3 then it should return ZERO count.
    Example Data:
    Col1 Col2 Col3
    abc 01 success
    abc 02 success
    abc 01 success
    abc 01 Failure
    abc 01 Error
    abc 02 Failure
    abc 03 Error
    xyz 07 Failure
    Required Output:
    c1 c2 s_cnt F_cnt E_cnt (Heading)
    abc 01 2 1 1
    abc 02 1 1 0
    abc 03 0 0 1
    xyz 07 0 1 0
    s_cnt = Success count; F_cnt = Failure count; E_cnt = Error count
    Please note that the output should have 5 columns with col1, col2, group by (col1,col2)count(success), group by (col1,col2)count(failure), group by (col1,col2)count(error)
    and where ever there are NO ROWS then it should return ZERO.
    Thanks in advance.
    Regards,
    Shiva

    Hi,
    user13015050 wrote:
    Thanks TTT. Unfortunately I cannot use this solution because I have huge data for this.T's solution is basically the same as mine. The first 23 lines just simulates your table. Since you actually have a table, you would start with T's line 24:
    SELECT col1 c1, col2 c2, SUM(decode(col3, 'success', 1, 0)) s_cnt, ...
    user13015050 wrote:Thanks a lot Frank. It helped me out. I just did some changes to this as below and have no issues.
    SELECT     col1
    ,     col2
    ,     COUNT ( CASE
              WHEN col3 = 'SUCCESS'
              THEN 1
              END
         )          AS s_cnt
    ,     COUNT ( CASE
              WHEN col3 = 'FAILED'
              THEN 1
              END
         )          AS f_cnt
    ,     COUNT ( CASE
              WHEN col3 = 'ERROR'
              THEN 1
              END
         )          AS e_cnt
    FROM     t1
    WHERE c2 in ('PURCHASE','REFUND')
    and c4 between to_date('20091031000000','YYYYMMDDHH24MISS') AND to_date('20100131235959','YYYYMMDDHH24MISS')
    GROUP BY c1, c2
    ORDER BY c1, c2;
    Please let me know if you see any issues in this query.It's very hard to read.
    This site normally compresses spaces. Whenever you post formatted text (such as queries or results) on this site, type these 6 characters:
    \(small letters only, inside curly brackets) before and after each section of formatted text, to preserve spacing.
    Also, post exactly what you're using.  The code above is SELECTing col1 and col2, but there's no mention of either in the GROUP BY clause, so I don't believe it's really what you're using.
    Other than that, I don't see anything wrong or suspicious in the query.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Sql query - Selecting last recorded values for each date in specified period

    Hello,
    Can someone please help me with my problem.
    I'm trying to get last recorded balance for each day for specific box (1 or 2) in specified period of days from ms access database using ADOTool.
    I'm trying to get that information with SQL query but so far unsuccessfully...  
    My table looks like this:
    Table name: TestTable
    Date Time Location Box Balance
    20.10.2014. 06:00:00 1 1 345
    20.10.2014. 12:00:00 1 1 7356
    20.10.2014. 18:45:00 1 1 5678
    20.10.2014. 23:54:00 1 1 9845
    20.10.2014. 06:00:02 1 2 35
    20.10.2014. 12:00:04 1 2 756
    20.10.2014. 18:45:06 1 2 578
    20.10.2014. 23:54:10 1 2 845
    21.10.2014. 06:00:00 1 1 34
    21.10.2014. 12:05:03 1 1 5789
    21.10.2014. 15:00:34 1 1 1237
    21.10.2014. 06:00:00 1 2 374
    21.10.2014. 12:05:03 1 2 54789
    21.10.2014. 15:00:34 1 2 13237
    22.10.2014. 06:00:00 1 1 8562
    22.10.2014. 10:00:00 1 1 1234
    22.10.2014. 17:03:45 1 1 3415
    22.10.2014. 22:00:00 1 1 6742
    22.10.2014. 06:00:05 1 2 562
    22.10.2014. 10:00:16 1 2 123
    22.10.2014. 17:03:50 1 2 415
    22.10.2014. 22:00:10 1 2 642
    23.10.2014. 06:00:00 1 1 9876
    23.10.2014. 09:13:00 1 1 223
    23.10.2014. 13:50:17 1 1 7768
    23.10.2014. 19:47:40 1 1 3456
    23.10.2014. 21:30:00 1 1 789
    23.10.2014. 23:57:12 1 1 25
    23.10.2014. 06:00:07 1 2 976
    23.10.2014. 09:13:45 1 2 223
    23.10.2014. 13:50:40 1 2 78
    23.10.2014. 19:47:55 1 2 346
    23.10.2014. 21:30:03 1 2 89
    23.10.2014. 23:57:18 1 2 25
    24.10.2014. 06:00:55 1 1 346
    24.10.2014. 12:30:22 1 1 8329
    24.10.2014. 23:50:19 1 1 2225
    24.10.2014. 06:01:00 1 2 3546
    24.10.2014. 12:30:26 1 2 89
    24.10.2014. 23:51:10 1 2 25
    Let's say the period is 21.10.2014. - 23.10.2014. and I want to get last recorded balance for box 1. for each day. The result should look like this:
    Date Time Location Box Balance
    21.10.2014. 15:00:34 1 1 1237
    22.10.2014. 22:00:00 1 1 6742
    23.10.2014. 23:57:12 1 1 25
    So far I've managed to write a query that gives me balance for ONLY ONE date (date with highest time in whole table), but I need balance for EVERY date in specific period.
    My incorrect code (didn't manage to implement "BETWEEN" for dates...):
    SELECT TestTable.[Date], TestTable.[Time], TestTable.[Location], TestTable.[Box], TestTable.[Balance]
    FROM TestTable
    WHERE Time=(SELECT MAX(Time)
    FROM TestTable
    WHERE Location=1 AND Box=1 );
    Tnx!
    Solved!
    Go to Solution.

    For loop
    following query keep day (here 24 in below query) Variable from ( 1 to 28-29/30/31 as per month)
    SELECT TOP 1 TestTable.[Date], TestTable.[Time], TestTable.[Location], TestTable.[Box], TestTable.[Balance]
    FROM Test Table.
    WHERE  Time=(SELECT MAX(Time) FROM TestTable WHERE Location=1 AND Box=1 )
    AND DATE = "2014-10-24";
    PBP (CLAD)
    Labview 6.1 - 2014
    KUDOS ARE WELCOMED.
    If your problem get solved then mark as solution.

  • Tricky SQL query... how to get all data in a single query?

    create table employee_definition (def_id number, def_name varchar(50));
    insert into employee_definition values (100, 'EMAIL');
    insert into employee_definition values (200, 'MOBILE_PHONE');
    insert into employee_definition values (300, 'HOME_PHONE');
    SQL> select * from employee_definition;
        DEF_ID DEF_NAME
           100 EMAIL
           200 MOBILE_PHONE
           300 HOME_PHONE
    create table employee_data (def_id number, def_value varchar(20), emp_id number);
    insert into employee_data values (100, '[email protected]', 123);
    insert into employee_data values (200, '01232222', 123);
    insert into employee_data values (300, '5555', 123);
    insert into employee_data values (100, '[email protected]', 666);
    insert into employee_data values (200, '888', 666);
    insert into employee_data values (300, '999', 666);
    insert into employee_data values (300, '444', 777);
    SQL> select * from employee_data;
        DEF_ID DEF_VALUE                EMP_ID
           100 [email protected]              123
           200 01232222                    123
           300 5555                        123
           100 [email protected]              666
           200 888                         666
           300 999                         666
           300 999                         777
    7 rows selected.I'm supposed to create a SQL that will return me the email, mobile_phone, and home_phone for a set of employees. The result will be something like this:
    EMPLOYEE ID | HOME_PHONE | MOBILE_PHONE | EMAIL
    123         |  5555  |    01232222      | [email protected]
    666         |  999  |    888      | [email protected]
    777         |  444  |    null     | nullThe thing I'm finding difficulty here is that the same column is used to store different values, based on the value in employee_definition table (something like a key/value pair). If I do:
    SQL> select emp_id, def_value as email from employee_data, employee_definition
      2  where employee_data.def_id = employee_definition.def_id
      3  and employee_definition.def_name = 'EMAIL';
        EMP_ID EMAIL
           123 [email protected]
           666 [email protected]'s partially ok.. I'm just getting the definition for 'EMAIL'. But how can I get all the values in a single query, knowing that the column stores different values based on def_name?

    Oh no, not again.
    Entity attribute models always seem like a great idea to people who have been in the profession for five minutes and lack any kind of fundamental knowledge.
    It staggers me that someone with 2,345 posts still believes "you need a 'detail table' for [storing multiple telephone numbers]"
    "A person can have multiple telephone numbers" is not an excuse to build a tired person_attribute table. Niether is the bizarre proposal by someone with over 4k posts who should know better in an earlier post that EAV models are necessary to support temporal fidelity.
    Taken to it's logical conclusion, EAV modelling leads to just two application tables. THINGS and THING_ATTRIBUTES. And when you consider that a THING_ATTRIBUTE is also a THING, why not roll those two tables up into one also? Hmmm, what does THINGS and THING_ATTRIBUTES look like? I know, TABLES and COLUMNS. Who would've guessed? SQL already provides the completely flexible extensible attribute model the advocates of EAV proscribe. But it also has data types, physical data independence, constraints and an efficient query language which EAV does not.
    EAV modelling errodes the semantics of the attributes which are bundled into the "attribute" table.
    There is no point in storing 12 different phone numbers with implied functional dependency to unconstrained and often repeating notional attributes like "MOBILE", "LANDLINE", "WORK", err, "WORK2", err, "MOBILE2", err, ... when this phone type attribute has no semantic value. When you want to call someone, you invariably want to retrive the prefered_phone_number which may depend on a time of day, or a call context.
    These things need to be modelled properly (i.e normalised to BCNF) within the context of the database.

  • To build dynamic SQL Query using some conditions: Pseudo code required

    Hi,
    I have a requirement where in i have to build a dynamic query based on one count.
    Some details on requirement:
    1) It's a Proc where i need to return some columns
    2) There are some fix set of columns
    3) Based on one Count column, i have to decide the rest of the columns.
    Consider there is an employee who can work on 'N' number of assignments.
    For a particular employee i have to return all the predefined details of assignments like:
    1) Assignment Name
    2) Assignmanet Id
    3) Assignemnt Start Date
    4) Assignment End Date
    This 'N' can vary from employee to employee. Based on which i have to return my result set. For instance if employee has 3 assignemnts, i have to return Fix columns( employee info) + (3*4) columns. Similarly if the employee has 4 assignments, i will be returning Fix columns + (4*4) columns.
    Certainly, the Employee ID is coming as an I/P parameter.
    The source table is a vertical table having all details of the employee assignments.
    Can anyone help me in coding this proc with the help of some pseudo code?

    Do you mean you need something like this to be executed dynamically for some known n := max(count(assignment_id))
    NOT TESTED !
    select e.dept_id,e.emp_id,e.epm_name,
           substr(x1,1,instr(x1,';',1,1) - 1) assignment_name_1,
           to_number(substr(x1,instr(x1,';',1,1) + 1,instr(x1,';',1,2) - instr(x1,';',1,1) - 1))) assignment_id_1,
           to_date(substr(x1,instr(x1,';',1,1) + 1,instr(x1,';',1,3) - instr(x1,';',1,2) - 1)),'yyyymmdd') assignment_start_date_1,
           to_date(substr(x1,instr(x1,';',1,1) + 1,instr(x1,';',1,3) + 1)),'yyyymmdd') assignment_end_date_1,
           substr(x2,1,instr(x2,';',1,1) - 1) assignment_name_2,
           to_number(substr(x2,instr(x2,';',1,1) + 1,instr(x2,';',1,2) - instr(x2,';',1,1) - 1))) assignment_id_2,
           to_date(substr(x2,instr(x2,';',1,1) + 1,instr(x2,';',1,3) - instr(x2,';',1,2) - 1)),'yyyymmdd') assignment_start_date_2,
           to_date(substr(x2,instr(x2,';',1,1) + 1,instr(x2,';',1,3) + 1)),'yyyymmdd') assignment_end_date_2,
           substr(xn,1,instr(xn,';',1,1) - 1) assignment_name_n,
           to_number(substr(xn,instr(xn,';',1,1) + 1,instr(xn,';',1,2) - instr(xn,';',1,1) - 1))) assignment_id_n,
           to_date(substr(xn,instr(xn,';',1,1) + 1,instr(xn,';',1,3) - instr(xn,';',1,2) - 1)),'yyyymmdd') assignment_start_date_n,
           to_date(substr(xn,instr(xn,';',1,1) + 1,instr(xn,';',1,3) + 1)),'yyyymmdd') assignment_end_date_n
      from (select e.dept_id,e.emp_id,e.epm_name,
                   max(decode(rnk,1,x)) x1,
                   max(decode(rnk,1,x)) x2,
                   max(decode(rnk,1,x)) xn
              from (select e.dept_id,e.emp_id,e.epm_name,
                           a.assignment_name||';'||to_char(a.assignment_id)||';'||
                           to_char(a.assignment_start_date,'yyyymmdd')||';'||to_char(a.assignment_end_date,'yyyymmdd') x,
                           dense_rank() over (partition by e.dept_id,e.emp_id,e.epm_name order by a.assignment_id) rnk
                      from employees e,assignments a
                     where e.emp_id = a.emp_id
             group by e.dept_id,e.emp_id,e.epm_name
           )Regards
    Etbin

  • SQL Query - Mapping Groups to Batches

    I am using Oracle 11g Release 2.
    I have the following dataset:
    CREATE TABLE RoomGroups
    (group_id NUMBER,
    group_name VARCHAR2(30),
    group_capacity NUMBER);
    INSERT INTO RoomGroups VALUES(1, 'SEECS UG Block', 100);
    INSERT INTO RoomGroups VALUES(2, 'IAEC Building', 70);
    INSERT INTO RoomGroups VALUES(3, 'RIMMS Building', 90);
    Commit;
    CREATE TABLE DegreeBatches
    (batch_id NUMBER, batch_name VARCHAR2(30), batch_strength NUMBER);
    INSERT INTO DegreeBatches VALUES(10,'BIT-10',35);
    INSERT INTO DegreeBatches VALUES(20,'BIT-11',40);
    INSERT INTO DegreeBatches VALUES(30,'BSCS-2',35);
    INSERT INTO DegreeBatches VALUES(40,'BSCS-3',40);
    INSERT INTO DegreeBatches VALUES(50,'BEE-4',50);
    INSERT INTO DegreeBatches VALUES(60,'BICSE-7',25);
    INSERT INTO DegreeBatches VALUES(70,'BESE-3',30);
    Commit;
    I want to achieve the following thr single or multiple SQL queries:
    Firstly, get all possible sets of DegreeBatches for each group - in such a way that for each set the SUM(batch_strength) <= Capacity of that group as show below.
    GroupId     Batches     StrengthStr     StrengthTotal     Capacity
    1.     {BIT-10, BIT-11, BICSE-7}     {35, 40, 25}     100     100
    1.     {BSCS-2, BSCS-3, BICSE-7}     {35, 40, 25}     100     100
    1.     {BEE-4, BSCS-3}     {50, 40}     90     100
    2.     {BIT-10, BSCS-2}     {35, 35}     70     70
    2.     {BSCS-3, BESE-3}     {40, 30}     70     70
    2.     {BIT-11, BICSE-7}     {40, 25}     65     70
    and so on...
    Secondly, I want to retrieve only non-overlapping sets based on minimum value of Capacity-StrengthTotal for each group
    GroupId     Batches     StrengthStr     StrengthTotal     Capacity
    1.     {BIT-10, BIT-11, BICSE-7}     {35, 40, 25}     100     100
    2.     {BSCS-3, BESE-3}     {40, 30}     70     70
    3.     {BSCS-2, BEE-4}     {35, 50}     85     90
    And finally, the final result must have all the batches in it...
    Which in this case is true...
    Any help will be highly appreciated...
    Thanks
    Bilal

    Is this not a duplicate thread?
    Re: SQL Query for mapping a set of batches to a class rooms group

Maybe you are looking for