SQL Query Help/ Converts seconds to day:hr:mi:se

I have query that returns value in seconds. How i will convert those seconds in DAY:HOUR:MIN:SEC in the same query? What will be the mathematical formulae or alogorithim for this?
Thanks
Munis Warsi
null

Seriously, you post 750+ lines of unformatted SQL statement and a completely unreadable and unformatted explain plan and you expect people to be able to help with that?
From what I can see it looks like some sort of query against an Oracle APPS database, and there are numerous calls to PL/SQL functions in there, so you're creating a multitude of context switches between the SQL and PL engines... that's known to cause performance problems.
Take a read of the discussions linked in the FAQ: Re: 3. How to  improve the performance of my query? / My query is running slow.
And also consider if your question would be better asked in the Oracle Apps forum space instead.

Similar Messages

  • Zimbra login is very slow - SQL query takes 35+ seconds

    Hi,
    my Zimbra login process remains very slow, 35-40 seconds with only a single user using it. I have Beehive set up as directory synchronized, with about 6500 users in it. However, I and a couple of colleagues the only ones making any use of it for testing. With just one person logging in, the following SQL query takes about 35 seconds to execute:
    SELECT /*+ LEADING(rf rf_pp) USE_NL(rf_pp) INDEX_ASC(@rf_connect_by rf@rf_connect_by (ws_real_folders.parent_eid ws_real_folders.eid)) */ RF.ENTERPRISE_ID AS
    ENTERPRISE_ID, RF.SITE_ID AS SITE_ID, RF.ENTITY_TYPE AS ENTITY_TYPE, RF.EID AS EID, RF.LOCK_ID AS LOCK_ID, RF.CACHE_ID AS CACHE_ID, RF.CACHE_TS AS
    CACHE_TS, RF.CACHE_SQ AS CACHE_SQ, FLOOR(RF.SECURE_CHECK/10) AS ACCESS_TYPES, RF.PARENT_ENTITY_TYPE AS PARENT_ENTITY_TYPE, RF.PARENT_EID AS
    PARENT_EID, RF.NAME AS NAME, RF.OWNER_ENTITY_TYPE AS OWNER_ENTITY_TYPE, RF.OWNER_EID AS OWNER_EID, RF.CREATED_ON AS CREATED_ON,
    RF.CREATOR_ENTITY_TYPE AS CREATOR_ENTITY_TYPE, RF.CREATOR_EID AS CREATOR_EID, RF.MODIFIEDON AS MODIFIED_ON, RF.MODIFIED_BY_ENTITY_TYPE AS
    MODIFIED_BY_ENTITY_TYPE, RF.MODIFIED_BY_EID AS MODIFIED_BY_EID, RF.VISIBILITY AS VISIBILITY, CASE WHEN (BITAND(:B13 , :B12 ) = :B12 ) THEN CAST(MULTISET(
    SELECT METADATA_CEN
    FROM OCS_ENTITY_METADATA_CENS_2_V META
    WHERE META.ENTITY_EID = RF.EID ) AS OCS_COLLAB_ID_TBL_T) ELSE CAST(NULL AS OCS_COLLAB_ID_TBL_T) END AS METADATA_CENS, CASE WHEN
    RF_PP.LAST_ACCESSED IS NULL THEN 'N' WHEN RF.MODIFIEDON > RF_PP.LAST_ACCESSED THEN 'U' ELSE NVL(RF_PP.RELATIVE_STATUS, 'N') END AS CHANGE_STATUS,
    RF.PROPERTIES AS PROPERTIES_CLOB, RF_PP.PROPERTIES AS VIEWERPROPERTIES_CLOB, RF.DESCRIPTION AS DESCRIPTION
    FROM (
    SELECT /*+ QB_NAME(rf_connect_by) no_connect_by_cost_based */ RF.ENTERPRISE_ID ENTERPRISE_ID, :B4 SITE_ID, :B3 ENTITY_TYPE, RF.EID EID, RF.LOCK_ID LOCK_ID,
    RF.ORA_ROWSCN CACHE_ID, RF.CACHE_TS CACHE_TS, RF.CACHE_SQ CACHE_SQ, RF.PARENT_TYPE PARENT_ENTITY_TYPE, RF.PARENT_EID PARENT_EID, RF.NAME
    NAME, RF.OWNER_TYPE OWNER_ENTITY_TYPE, RF.OWNER_EID OWNER_EID, RF.CREATED_ON CREATED_ON, RF.CREATOR_TYPE CREATOR_ENTITY_TYPE,
    RF.CREATOR_EID CREATOR_EID, RF.MODIFIED_ON MODIFIEDON, RF.MODIFIED_BY_TYPE MODIFIED_BY_ENTITY_TYPE, RF.MODIFIED_BY_EID MODIFIED_BY_EID,
    RF.VISIBILITY VISIBILITY, RF.PROPERTIES PROPERTIES, RF.DESCRIPTION DESCRIPTION, RF.IS_HIDDEN IS_HIDDEN, LEVEL LEVEL_NUM, COALESCE (
    (SELECT :B10 * 10 + 1
    FROM AC_ENTITIES AEI
    WHERE RF.EID = AEI.EID AND ( 1 = DECODE(AEI.SENSITIVITY_EID, :B9 , 1, 0) AND 1 = DECODE(AEI.OWNER_EID, :B8 , 1, 0) AND 1 = DECODE(AEI.AT_READ, :B7 , 1, 0) AND 1 =
    DECODE(AEI.AT_DISCOVER, :B6 , 1, 0) AND 1 = DECODE(AEI.LOCAL_ACL_ID, :B5 , 1, 0) ) ) ,
    (SELECT ACV.ACCESS_TYPES * 10 + ACV.IS_ALLOWED
    FROM AC_CHECK_ONE_OF_V ACV
    WHERE ACV.EID = RF.EID ) ) SECURE_CHECK
    FROM WS_REAL_FOLDERS RF
    WHERE RF.IS_HIDDEN = :B2 START WITH RF.PARENT_EID = :B1 CONNECT BY PRIOR RF.EID = RF.PARENT_EID ) RF, WS_RF_PRVT_PROPERTIES RF_PP
    WHERE RF.EID = RF_PP.EID (+) AND :B11 = RF_PP.VIEWER_EID (+) AND 1 = BITAND(RF.SECURE_CHECK, 1) ORDER BY RF.LEVEL_NUMIt has ID atrvjdrmz2v6d in Enterprise Manager, and I've tried tuning it with the SQL tuning advisor in EM. I did the statistics gathering mentioned in another thread yesterday, to see if that helped - doesn't seem liked it. I'm running Database 11.1.0.6 and Beehive 1.5.1 in the build from the day it released.
    Any hints? I'll post this to MetaLink as well, unless someone has some immediate idea what's wrong :-)

    No speedup, the 35-40 seconds is for normal logins - and it's very consistent, at least if the database is otherwise idle. Immediately logging out and back in gives me the same wait, and the same query shows up in the Enterprise Manager interface.
    It seems it might be related to Workspaces - from EM:
    "PL/SQL Source (Line Number)          BEE_CODE.WS_REAL_FOLDER_PKG (2998)"

  • SQL Query Help - Is this possible or impossible????

    Hi guys,
    I need help with an SQL query that I'm trying to develop. It's very easy to explain but when trying to implement it, I'm struggling to achieve the results that I want.....
    For example,
    I have 2 tables
    The first table is:
    1) COMPANY create table company (manufacturer varchar2(25),
                                                          date_established date,
                                                          location varchar2(25) );My sample test date is:
    insert into company values ('Ford', 1902, 'USA');
    insert into company values ('BMW', 1910, 'Germany');
    insert into company values ('Tata', 1922, 'India');The second table is:
    2) MODELS create table models (manufacturer varchar(25),
                                                 model varchar2(25),
                                                 price number(10),
                                                 year date,
                                                 current_production_status varchar2(1) ) ;My sample test data is:
    insert into models values ('Ford', 'Mondeo', 10000, 2010, 0);
    insert into models values ('Ford', 'Galaxy', 12000,   2008, 0);
    insert into models values ('Ford', 'Escort', 10000, 1992, 1);
    insert into models values ('BMW', '318', 17500, 2010, 0);
    insert into models values ('BMW', '535d', 32000,   2006, 0);
    insert into models values ('BMW', 'Z4', 10000, 1992, 0);
    insert into models values ('Tata', 'Safari', 4000, 1999, 0);
    insert into models values ('Tata', 'Sumo', 5500,   1996, 1);
    insert into models values ('Tata', 'Maruti', 3500, 1998, 0);And this is my query:
    SELECT
            com.manufacturer,
            com.date_established,
            com.location,
            DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.model),
            DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.price),
            DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.year),
            mod.current_production_status
    FROM
           company com,
           models mod
    WHERE
          mod.manufacturer = com.manufacturer
          and com.manufacturer IN ('Ford', 'BMW', 'Tata')
          and mod.current_production_status IN (1,0)
    ORDER BY
            mod.current_production_status DESCWhat I want the query to output is this:
    com.manufacturer        com.date_established          com.location          mod.model          mod.price             mod.year     mod.current_production_status
    Ford               1902                    USA               Escort               10000               1992          1
    BMW               1910                    Germany               -               -               -          0
    Tata               1922                    India               Sumo               5500               1998          1If current_production_status is 1 it means this particular model has been discontinued
    If current_production_status is 0 it means the manufacturer does not have any discontinued models and all are in procuction.
    The rule is only one record per manufacturer is allowed to have a current_production_status of 1 (so only one model from the selection the manufactuer offers is allowed to be discontinued).
    So the query should output the one row where current_production_status is 1 for each manufacturer.
    If for a given manufacturer there are no discontinued models and all have a current_production_status of 0 then ouput a SINGLE row that only includes the data from the COMPANY table (as above). The rest of the columns from the MODELS table should be populated with a '-' (hyphen).
    My query as it is above will output all the records where current status is 1 or 0 like this
    com.manufacturer        com.date_established          com.location          mod.model          mod.price          mod.year     mod.current_production_status
    Ford               1902                    USA               Escort               10000               1992          1
    Tata               1922                    India               Sumo               5500               1998          1
    Ford               1902                    USA               -               -               -          0                    
    Ford               1902                    USA               -               -               -          0
    BMW               1910                    Germany               -               -               -          0
    BMW               1910                    Germany               -               -               -          0
    BMW               1910                    Germany               -               -               -          0
    Tata               1922                    India               -               -               -          0
    Tata               1922                    India               -               -               -          0However this is not what I want.
    Any ideas how I can achieve the result I need?
    Thanks!
    P.S. Database version is '10.2.0.1.0'

    Hi Vishnu,
    Karthiks query helped...
    But this is the problem I am facing...
    SELECT
            com.manufacturer,
            com.date_established,
            com.location,
            DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.model),
            DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.price),
            DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.year),
            mod.current_production_status
    FROM
           company com,
           models mod
    WHERE
          mod.manufacturer = com.manufacturer
          and com.manufacturer = 'Ford'
          and mod.current_production_status IN (1,0)
    ORDER BY
            mod.current_production_status DESCThe value of:
    and com.manufacturer = 'Ford'will be dependent on front end user input....
    When I run the query above I get all the rows where current_production_status is either 1 or 0.
    I only require the rows where current_production_status is 1.
    So if I amend it to look like this:
         and mod.current_production_status = 1This works....
    BUT if a user now passes in more than one manufacturer EG:
    and com.manufacturer IN ('Ford', 'BMW')The query will only return the one row for Ford where current_production_status is 1. However because BMW has no models where current_production_status is 1 (all 3 are 0), I still want this to be output - as one row....
    So like this:
    com.manufacturer        com.date_established          com.location          mod.model          mod.price             mod.year     mod.current_production_status
    Ford               1902                    USA               Escort               10000               1992          1
    BMW               1910                    Germany               -               -               -          0So (hopefully you understand), I want both cases to be catered for.....whether a user enters one manufacturer or more than one...
    Thanks you so much!
    This is really driving me insane :-(

  • Converting seconds to Days,Hours,mins and secs

    Hi gurus,
    I have a metric in seconds , which is a box uptime . I want to convert that into Days,hours , mins and secs .How can I do that ?
    For example , If I have 433500 secs , I should show it as 5days 00:25:00 or in some meaningful format . Can anyone help me out ?
    Thanks,

    Hi,
    Refer thinks,
    Re: seconds to hh:mm:ss format
    OBIEE 11g - Change seconds to DD HH:MM:SS format
    Deva

  • SQL Query Help Needed

    I'm having trouble with an SQL query. I've created a simple logon page wherein a user will enter their user name and password. The program will look in an Access database for the user name, sort it by Date/Time modified, and check to see if their password matches the most recent password. Unfortunately, the query returns no results. I'm absolutely certain that I'm doing the query correctly (I've imported it directly from my old VB6 code). Something simple is eluding me. Any help would be appreciated.
    private void LogOn() {
    //make sure that the user name/password is valid, then load the main menu
    try {
    //open the database connection
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection con = DriverManager.getConnection("jdbc:odbc:LawOffice2000", "", "");
    Statement select = con.createStatement();
    String strTemp = "Select * From EMPLOYEES Where INITIALS = '" + txtUserName.getText() + "' Order By DATE Desc, TIME Desc";
    ResultSet result = select.executeQuery(strTemp);
    while(result.next()) {
    if (txtPassword.getPassword().toString() == result.getString("Password")) {
    MenuMain.main();
    else {
    System.out.println("Password Bad");
    System.out.println(txtUserName.getText());
    System.out.println(result.getString("Password"));
    break; //exit loop
    //close the connection
    con.close(); }
    catch (Exception e) {
    System.out.println("LawOfficeSuite_LogOn: " + e);
    return; }
    }

    The problem is here: "txtPassword.getPassword().toString() == result.getString("Password"))"
    Don't confuse String's equals() method with the equality operator '=='. The == operator checks that two references refer to the same object. If you want to compare the contents of Strings (whether two strings contain the same characters), use equals(), e.g. if (str1.equals(str2))...
    Example:String s1 = "foo";
    String s2 = new String("foo");
    System.out.println("s1 == s2: " + (s1 == s2)); // false
    System.out.println("s1.equals(s2): " + (s1.equals(s2))); // trueFor more information, check out Comparison operators: equals() versus ==

  • Sql query - been trying for two days

    Hi guys im trying to carry out an sql query
    Im using a left join to do a query, which gives me a set of results:
    select COURSESTUDENT.StudentNo, COURSESTUDENT.CourseCode, COURSESTUDENT.Year, MARKS.ExamMark, MARKS.EntryNo FROM COURSESTUDENT LEFT JOIN MARKS ON COURSESTUDENT.StudentNo=MARKS.StudentNo AND COURSESTUDENT.CourseCode=MARKS.CourseCode AND COURSESTUDENT.Year=MARKS.Year
    but I would like to do a select on this result but do not want to use a create view as if more than one person access this page at a time then if the servlet tries to create the view an error will occur.
    I would like to do the following select statement on the results of the query above..
    select * from (above) where CourseCode='ELE304' AND Year=1999;
    Is this possible, im using postgres..
    Please help......
    thanks
    tzaf

    just add "where ..." to the end of the first query.

  • Sql query - help reqd

    Hi,
    I require help for sql query. The query will be like
    "SELECT * FROM XYZ WHERE TEXT = 'h*s' "
    and the results will be come like
    “his”
    “homes”
    “houses”
    “horses”,
    “horticulturalists”
    “herbaceous”.
    Thanks,
    Kapil

    Hello,
    SELECT   *
      FROM   XYZ
    WHERE   TEXT LIKE ('h%s');Regards
    Edited by: OrionNet on Feb 2, 2009 12:33 AM

  • Convert seconds to Days, hours, Minutes, Seconds in Reporting Services

    Hi Guys,
    Im currently reporting of an analysis services cube, however I have value which is in seconds and would like to report on this in reporting services as day:HH:MM:SS.
    Has anyone got any experience reporting in this format?
    Regards
    Dave

    Hi Dave,
    We can use custom code to convert seconds to HH:MM:SS
    Public Function Calculate(ByVal TotalSeconds as Integer) as String
    Dim Hours, Minutes, Seconds As Integer
    Dim Hour, Minute, Second As String
    Hours = floor(TotalSeconds/ 3600)
    IF Hours<10
       Hour="0" & Hours.ToString
    Else
       Hour=Hours.ToString
    End IF
    Seconds = TotalSeconds Mod 3600
    Minutes =floor( Seconds / 60)
    IF Minutes<10
       Minute="0" & Minutes.ToString
    Else
       Minute=Minutes.ToString
    End IF
    Seconds = Seconds Mod 60
    IF Seconds<10
       Second="0" & Seconds.ToString
    Else
       Second=Seconds.ToString
    End IF
    Return Hour & ":" & Minute & ":" & Second
    End Function
    Then we can use the expression to conver it.
    =Code.Calculate(Fields!Column.Value)
    The report looks like below:
    If you have any questions, please feel free to ask.
    Regards,
    Charlie Liao
    If you have any feedback on our support, please click
    here.
    Charlie Liao
    TechNet Community Support

  • SQL Query to convert multiple rows to a single row output

    I have the following sql query;
    SELECT B.ClientID,
    B.BillNo, B.[BillDate],
    B.CurrencyCode,
    B.BAmount
    FROM tblCompanyDetails CD
    CROSS
    APPLY (
    SELECT TOP 5 B1.ClientID,
     B1.[BillNumber],
    B1.[BillDate], B1.[CurrencyCode] AS CCY,
     B1.[BillAmount]
    FROM tblBills B1
    WHERE ROUND(B1.[BillAmount],2)<>0
    AND B1.ClientID=CD.CompanyID
    AS B
    WHERE CD.ContactId=235405
    ORDER
    BY B.ClientID,B.BillNo
    DESC
    This gives me the following row output;
    ClientID
    BillNo
    BillDate
    CurrencyCode
    BAmount
    94466
    425616
    2015-04-07
    GBP
    5000
    94466
    424517
    2015-01-15
    GBP
    6000
    94466
    424455
    2014-10-15
    GBP
    4000
    However, I would like the ouput to appear like this;
    ClientID
    BillNo1
    BillDate
    CCY
    BAmount
    BillNo2
    BillDate
    CCY
    BAmount
    BillNo3
    BillDate
    CCY
    BAmount
    94466
     425616
     2015-04-07
     GBP
     5000
     424517
     2015-01-15
     GBP
     6000
     424455
     2014-10-15
     GBP
    4000 

    I have tried to create a sample based on your question
    CREATE TABLE MyTable
    ClientID INT ,
    BillNo INT,
    BillDate DATE,
    CurrencyCode varchar(5),
    BAmount INT
    INSERT INTO MyTable
    VALUES (94466,425616,'2015-04-07','GBP',5000),
    (94466,424517,'2015-01-15','GBP',6000),
    (94466,424455,'2014-10-15','GBP',4000)
    Then I have used another table to put ranking in that, you can actually tweak your statement to include rank also
    CREATE TABLE RowTable
    ClientID INT ,
    BillNo INT,
    BillDate DATE,
    CurrencyCode varchar(5),
    BAmount INT,
    Ranking INT
    INSERT INTO RowTable
    SELECT * , ROW_NUMBER() OVER (ORDER BY ClientID) as row
    FROM MyTable
    Once your data is ready then execute below dynamic query
    DECLARE @cols AS NVARCHAR(MAX),
    @query AS NVARCHAR(MAX)
    select @cols = STUFF((SELECT ',' + QUOTENAME(col+cast(Ranking as varchar(10)))
    from RowTable
    cross apply
    select 'BillNo', 1 union all
    select 'BillDate', 2 union all
    select 'CurrencyCode', 3 union all
    select 'BAmount' , 4
    ) c (col, so)
    group by col, so, Ranking
    order by Ranking, so
    FOR XML PATH(''), TYPE
    ).value('.', 'NVARCHAR(MAX)')
    ,1,1,'')
    set @query = 'SELECT ClientId,' + @cols + '
    from
    select clientid, col+cast(Ranking as varchar(10)) col, value
    from RowTable
    cross apply
    SELECT ''BillNo'', cast(BillNo as varchar(20)) union all
    SELECT ''BillDate'', cast(BillDate as varchar(20)) union all
    SELECT ''CurrencyCode'', CurrencyCode union all
    SELECT ''BAmount'', CAST(BAmount as varchar(10))
    ) c (col, value)
    ) x
    pivot
    max(value)
    for col in (' + @cols + ')
    ) p '
    execute sp_executesql @query;
    Output: 
    Hope this will help. 

  • Sql query - help reqd (new)

    Hi,
    I have follwing dataset
    "herb with garden"
    "garden without herb"
    "herb with zbc"
    "garden with pqr"
    Now i want sql query like
    select * from table where text1 = "herb and garden"
    This should populate
    herb with garden
    garden without herb
    And
    select * from table where text1 = "herb or garden"
    This should populate
    "herb with garden"
    "garden without herb"
    "herb with zbc"
    "garden with pqr"

    SQL> with t
      2  as
      3  (
      4     select 'herb with garden' str from dual union all
      5     select 'garden without herb' str from dual union all
      6     select 'herb with zbc' str from dual union all
      7     select 'garden with pqr' str from dual
      8  )
      9  select *
    10    from t
    11   where lower(str) like '%herb%'
    12     and lower(str) like '%garden%'
    13  /
    STR
    herb with garden
    garden without herb
    SQL> with t
      2  as
      3  (
      4     select 'herb with garden' str from dual union all
      5     select 'garden without herb' str from dual union all
      6     select 'herb with zbc' str from dual union all
      7     select 'garden with pqr' str from dual
      8  )
      9  select *
    10    from t
    11   where lower(str) like '%herb%'
    12     or lower(str) like '%garden%'
    13  /
    STR
    herb with garden
    garden without herb
    herb with zbc
    garden with pqr

  • Need sql query to convert rows to columns

    Im using oracle 11g.
    I have data in a table as below: Column names are type,month,percentage
    TYPE      MONTH   PERCENTAGE
    A1         JAN-2013     100
    A2         JAN-2013     100
    A3         JAN-2013     95
    A4         JAN-2013     98
    A5         JAN-2013     99
    A6         JAN-2013     90
    A7         JAN-2013     92
    A1         FEB-2013     100
    A2         FEB-2013     99
    A3         FEB-2013     88
    A4         FEB-2013     67
    A5         FEB-2013     98
    A6         FEB-2013     95
    A7         FEB-2013     84
    The desired output using a sql query is as below
    TYPE     JAN-2013     FEB-2013
    A1         100             100
    A2         100             99
    A3         95               88
    A4         98               67
    A5         99               98
    A6         90               95
    A7         92               84

    Try this:
    select * from table_name
    PIVOT(   max(Percentage)
                     for MONTH
                     in ('JAN-2013','FEB-2013')
                     ) ;with data
    with t(TYPE,MONTH,PERCENTAGE) as
    SELECT 'A1', 'JAN-2013', 100
      FROM DUAL
    UNION ALL
    SELECT 'A2', 'JAN-2013', 100
      FROM DUAL
    UNION ALL
    SELECT 'A3', 'JAN-2013', 95
      FROM DUAL
    UNION ALL
    SELECT 'A4', 'JAN-2013', 98
      FROM DUAL
    UNION ALL
    SELECT 'A1', 'FEB-2013', 100
      FROM DUAL
    UNION ALL
    SELECT 'A2', 'FEB-2013', 99
      FROM DUAL
    UNION ALL
    SELECT 'A3', 'FEB-2013', 88
      FROM DUAL
    UNION ALL
    SELECT 'A4', 'FEB-2013', 67
      FROM DUAL
    select * from t PIVOT(   max(Percentage)
                     for MONTH
                     in ('JAN-2013','FEB-2013')
                     ) ;

  • Sql query help

    hi guys
    i have sample data as mentioned below... need to find the duplicate rows where cd=cd and dt1=dt1 and tm1 difference should be less than or equal to 4 hrs..
    i can get the data with the query written below but my problem is that i am not allowed to use in-built sql server function... can you help me in writing the same without using in-built function...
    CREATE TABLE #t (id INT,dt1 datetime, tm1 datetime,cd varchar(10))
    INSERT INTO #t VALUES (101,'2013-04-24','1900-01-01 12:20:00.000','TC')
    INSERT INTO #t VALUES (101,'2013-04-24','1900-01-01 12:30:00.000','TC')
    INSERT INTO #t VALUES (101,'2013-08-02','1900-01-01 14:30:00.000','MN')
    INSERT INTO #t VALUES (101,'2013-08-02','1900-01-01 15:07:00.000','MN')
    INSERT INTO #t VALUES (101,'2013-07-06','1900-01-01 09:07:00.000','XY')
    INSERT INTO #t VALUES (101,'2013-11-27','1900-01-01 09:50:00.000','LM')
    INSERT INTO #t VALUES (101,'2013-07-06','1900-01-01 15:07:00.000','XY')
    select * From #t
    WITH MyCTE (rn,id, dt1, tm1, cd)
    AS(
    select row_number() over (partition by id ORDER BY dt1, tm1) rn,* from #t
    select case when ((dt1 = lead_start_Date) and (ct <='4.0') and (base_cd = lead_cd)) then 'Duplicate_Req' else '' end dt123,* from
    select abs(convert(decimal(5,1),datediff(MI,lead_Start_time,tm1)/60.00)) ct, * from
    SELECT base.rn b_rn,LEAd.rn l_rn,BASE.id
    ,BASE.dt1
    ,BASE.tm1
    ,base.cd base_cd
    ,LEAD.dt1 LEAD_START_DATE
    ,LEAD.tm1 LEAD_START_TIME
    ,lead.cd lead_cd
    --,DATEADD(dd,-1,LEAD.dt1) EXPECTED_END_DATE
    FROM MyCTE BASE
    LEFT JOIN MyCTE LEAD ON BASE.id = LEAD.id
    AND BASE.rn = LEAD.rn+1
    ) b
    )c

    if this code will not work for you then not sure if there are any other options
    Converted the CTE into an actual temp table.
    CTE and barebones T-SQL code are included in the script below.
    CREATE TABLE #t (id INT,dt1 datetime, tm1 datetime,cd varchar(10))
    INSERT INTO #t VALUES (101,'2013-04-24','1900-01-01 12:20:00.000','TC')
    INSERT INTO #t VALUES (101,'2013-04-24','1900-01-01 12:30:00.000','TC')
    INSERT INTO #t VALUES (101,'2013-08-02','1900-01-01 14:30:00.000','MN')
    INSERT INTO #t VALUES (101,'2013-08-02','1900-01-01 15:07:00.000','MN')
    INSERT INTO #t VALUES (101,'2013-07-06','1900-01-01 09:07:00.000','XY')
    INSERT INTO #t VALUES (101,'2013-11-27','1900-01-01 09:50:00.000','LM')
    INSERT INTO #t VALUES (101,'2013-07-06','1900-01-01 15:07:00.000','XY')
    INSERT INTO #t VALUES (101,'2013-08-02','1900-01-01 15:07:00.000','MN')
    select * From #t
    ;WITH MyCTE (rn,id, dt1, tm1, cd)
    AS(
    select row_number() over (partition by id ORDER BY dt1, tm1) rn,* from #t
    select case when ((dt1 = lead_start_Date) and (ct <='4.0') and (base_cd = lead_cd)) then 'Duplicate_Req' else '' end dt123,* from
    select abs(convert(decimal(5,1),datediff(MI,lead_Start_time,tm1)/60.00)) ct, * from
    SELECT base.rn b_rn,LEAd.rn l_rn,BASE.id
    ,BASE.dt1
    ,BASE.tm1
    ,base.cd base_cd
    ,LEAD.dt1 LEAD_START_DATE
    ,LEAD.tm1 LEAD_START_TIME
    ,lead.cd lead_cd
    --,DATEADD(dd,-1,LEAD.dt1) EXPECTED_END_DATE
    FROM MyCTE BASE
    LEFT JOIN MyCTE LEAD ON BASE.id = LEAD.id
    AND BASE.rn = LEAD.rn+1
    ) b
    )c
    select * into #copy From #t order by id, cd, dt1, tm1
    alter table #copy add seqno int identity(1,1)
    select distinct y.id,y.cd,y.dt1,y.tm1,y.seqno,case when z.cd is not null then 'Duplicate_Req' else '' end dt123
    from #copy y
    left outer join
    (select a.id,a.cd,a.dt1,a.tm1
    From #copy a
    left outer join #copy b
    on a.id = b.id
    and a.cd = b.cd
    and a.dt1 = b.dt1
    where a.seqno > b.seqno
    and abs(datediff(MINUTE,b.tm1,a.tm1)) <= 240) z
    on y.id = z.id
    and y.cd = z.cd
    and y.dt1 = z.dt1
    and y.tm1 = z.tm1
    order by y.dt1,y.tm1
    drop table #copy
    drop table #t

  • Complex SQL query help

    Hi,
    I was wondering if I could have some help with the query I have below for this general data set, please? I need to do it in a single SQL statement. We're currently running Oracle 10g. The piece I'm struggling with is identifying that the person has all the items in a collection and to include the collection in the resulting collection of items.
    persons_items
    person     item
    Ted          cup
    Ted          saucer
    Ted          plate
    Ted          fork
    Alice          book
    Alice          thimble
    Alice          knife
    Alice          cup
    Joe          cup
    Joe          saucer
    Joe          plate
    Joe          knife
    Joe          fork
    Joe          spoon
    Jessica     spatula
    Jessica     dish
    collections
    collection_name     item
    crockery     cup
    crockery     saucer
    crockery     plate
    cutlery          knife
    cutlery          fork
    cutlery          spoon
    Query:
    What single items and collections does Ted have?     fork, crockery
    What single items and collections does Alice have?     book, thimble, knife, cup
    What single items and collections does Joe have?     crockery, cutlery
    What single items and collections does Jessica have?     spatula, dish
    Thanks in advance.
    Pat

    Expanding on Brendan's solution...
    For 11g:
    SQL> ed
    Wrote file afiedt.buf
      1  WITH person_items AS (
      2          SELECT 'Ted' person, 'cup' item FROM DUAL UNION
      3          SELECT 'Ted', 'saucer' FROM DUAL UNION
      4          SELECT 'Ted', 'plate' FROM DUAL UNION
      5          SELECT 'Ted', 'fork' FROM DUAL UNION
      6          SELECT 'Alice', 'book' FROM DUAL UNION
      7          SELECT 'Alice', 'thimble' FROM DUAL UNION
      8          SELECT 'Alice', 'knife' FROM DUAL UNION
      9          SELECT 'Alice', 'cup' FROM DUAL UNION
    10          SELECT 'Joe', 'cup' FROM DUAL UNION
    11          SELECT 'Joe', 'saucer' FROM DUAL UNION
    12          SELECT 'Joe', 'plate' FROM DUAL UNION
    13          SELECT 'Joe', 'knife' FROM DUAL UNION
    14          SELECT 'Joe', 'fork' FROM DUAL UNION
    15          SELECT 'Joe', 'spoon' FROM DUAL UNION
    16          SELECT 'Jessica', 'spatula' FROM DUAL UNION
    17          SELECT 'Jessica', 'dish' FROM DUAL
    18  ), collections AS (
    19          SELECT 'crockery' collection_name, 'cup' item FROM DUAL UNION
    20          SELECT 'crockery', 'saucer' FROM DUAL UNION
    21          SELECT 'crockery', 'plate' FROM DUAL UNION
    22          SELECT 'cutlery', 'knife' FROM DUAL UNION
    23          SELECT 'cutlery', 'fork' FROM DUAL UNION
    24          SELECT 'cutlery', 'spoon' FROM DUAL
    25  ), person_item_colls AS (
    26          SELECT pi.person, pi.item, co.collection_name,
    27                 Count(*) OVER (PARTITION BY pi.person, co.collection_name) n_col
    28            FROM person_items pi
    29            LEFT JOIN collections co
    30              ON co.item = pi.item
    31  )
    32  select person, listagg(collection_name,',') within group (order by collection_name) as collections
    33  from (
    34        SELECT DISTINCT person, collection_name
    35        FROM   person_item_colls
    36        WHERE  collection_name IS NOT NULL
    37        AND    n_col > 1
    38        UNION ALL
    39        SELECT person, item
    40        FROM   person_item_colls
    41        WHERE  collection_name IS NULL
    42        OR     n_col = 1
    43       )
    44* group by person
    SQL> /
    PERSON  COLLECTIONS
    Alice   book,cup,knife,thimble
    Jessica dish,spatula
    Joe     crockery,cutlery
    Ted     crockery,forkFor 10g:
    SQL> ed
    Wrote file afiedt.buf
      1  WITH person_items AS (
      2          SELECT 'Ted' person, 'cup' item FROM DUAL UNION
      3          SELECT 'Ted', 'saucer' FROM DUAL UNION
      4          SELECT 'Ted', 'plate' FROM DUAL UNION
      5          SELECT 'Ted', 'fork' FROM DUAL UNION
      6          SELECT 'Alice', 'book' FROM DUAL UNION
      7          SELECT 'Alice', 'thimble' FROM DUAL UNION
      8          SELECT 'Alice', 'knife' FROM DUAL UNION
      9          SELECT 'Alice', 'cup' FROM DUAL UNION
    10          SELECT 'Joe', 'cup' FROM DUAL UNION
    11          SELECT 'Joe', 'saucer' FROM DUAL UNION
    12          SELECT 'Joe', 'plate' FROM DUAL UNION
    13          SELECT 'Joe', 'knife' FROM DUAL UNION
    14          SELECT 'Joe', 'fork' FROM DUAL UNION
    15          SELECT 'Joe', 'spoon' FROM DUAL UNION
    16          SELECT 'Jessica', 'spatula' FROM DUAL UNION
    17          SELECT 'Jessica', 'dish' FROM DUAL
    18  ), collections AS (
    19          SELECT 'crockery' collection_name, 'cup' item FROM DUAL UNION
    20          SELECT 'crockery', 'saucer' FROM DUAL UNION
    21          SELECT 'crockery', 'plate' FROM DUAL UNION
    22          SELECT 'cutlery', 'knife' FROM DUAL UNION
    23          SELECT 'cutlery', 'fork' FROM DUAL UNION
    24          SELECT 'cutlery', 'spoon' FROM DUAL
    25  ), person_item_colls AS (
    26          SELECT pi.person, pi.item, co.collection_name,
    27                 Count(*) OVER (PARTITION BY pi.person, co.collection_name) n_col
    28            FROM person_items pi
    29            LEFT JOIN collections co
    30              ON co.item = pi.item
    31  )
    32  select person, ltrim(sys_connect_by_path(collection_name,','),',') as collections
    33  from (
    34        select person, collection_name, row_number() over (partition by person order by collection_name) as rn
    35        from (
    36              SELECT DISTINCT person, collection_name
    37              FROM   person_item_colls
    38              WHERE  collection_name IS NOT NULL
    39              AND    n_col > 1
    40              UNION ALL
    41              SELECT person, item
    42              FROM   person_item_colls
    43              WHERE  collection_name IS NULL
    44              OR     n_col = 1
    45             )
    46        )
    47  where connect_by_isleaf = 1
    48  connect by person = prior person and rn = prior rn + 1
    49* start with rn = 1
    SQL> /
    PERSON  COLLECTIONS
    Alice   book,cup,knife,thimble
    Jessica dish,spatula
    Joe     crockery,cutlery
    Ted     crockery,fork

  • Urgent SQL query help

    Hello,
    I need help with SQL... My database version is Oracle 10g Release 1.2.
    I have two table with the exact same structure as follows...
    create table t1(cust_id number(5), zone_number number(2), part_number varchar2(10))
    create table t2(cust_id number(5), zone_number number(2), part_number varchar2(10))
    I need a query that would give me two counts per pairs of customer between t1 and t2..
    1.Count of part_number matches between the same zones in table 1 and table 2 for pairs of customers
    for Customer 1 and 10 for zone 1 this total shoulb be 2 because between cust 1 and 10 for Zone 1 there are two part number matches A and B.
    for Customer 1 and 10 for zone 2 this total shoulb be 0 because between cust 1 and 10 for Zone 2 there are no part number matches
    for Customer 1 and 20 for zone 1 this total shoulb be 0 because between cust 1 and 20 for Zone 1 there are no part number matches
    for Customer 1 and customer 20 zone 2 this total shoulb be 0 because between cust 1 and 20 for Zone 2 there is one part number matches , which is 'F'
    for Customer 1 and customer 20 zone 3 this total shoulb be 0 because there is no zone 3 for Customer 1
    same way
    .. cust 2 and cust 10 Zone 1 counts and zone2 counts
    .. for 2 and cust 20 zone 1, 2, and 3 counts
    2. Total unique Part nmbers between the same zones for pairs of customers in table 1 and table2
    for example
    unique part numbers between cust 1 and 10 for zone 1 are A,B and C so the count should be 3
    unique part numbers between cust 1 and 10 for zone 2 are B,F, D and E so the count should be 3
    unique part numbers between cust 1 and 20 for zone 1 are A,B,C and G so the count should be 4
    and so on so forth
    insert into t1 values(1, 1, 'A')
    insert into t1 values(1, 1, 'B')
    insert into t1 values(1, 1, 'C')
    insert into t1 values(1, 2, 'B')
    insert into t1 values(1, 2, 'F')
    insert into t1 values(1, 2, 'D')
    insert into t1 values(1, 2, 'E')
    insert into t1 values(2, 1, 'F')
    insert into t1 values(2, 2, 'G')
    insert into t1 values(2, 2, 'H')
    insert into t2 values(10, 1, 'A')
    insert into t2 values(10, 1, 'B')
    insert into t2 values(10, 2, null)
    insert into t2 values(20, 1, 'G')
    insert into t2 values(20, 2, 'F')
    insert into t2 values(20, 2, 'H')
    insert into t2 values(20, 3, 'I')
    insert into t2 values(20, 3, 'J')
    My query result should be as follows...
    cust1 cust2 zone pn_match_count total_unique_pn_count
    1 10 1 2 3
    1 10 2 0 4
    1 20 1 0 4
    1 20 2 1 5
    1 20 3 0 2
    2 10 1 0 3
    2 10 2 0 2
    2 20 1 0 2
    2 20 2 1 3
    2 20 3 0 2
    I would really appreciate your help in writing this query.
    Thanks in Advance

    user00 wrote:
    No, that doesn't do it... I get no results with this query becuase the Cust_id in table 1 and table 2 are not the same.Yeah, I only realised that after I posted my query. I had interpreted pairs as "matching pairs" when what you meant was "permutations".
    Cheers, APC
    blog: http://radiofreetooting.blogspot.com

  • SQL QUERY HELP PLZZZ

    My requirement is to calculate few things like total_cash_amount,TOTAL_CO_PATIENT_AMOUNT etc... FOr this we will be using BILLING.PATIENTBILL,BILLING.PATIENTBILLDETAILS,BILLING.TRANSACTION tables. The below is already developed procedure.
    I am askd to modify the same for the better performance. The below is the part of it i.e. calculation of total_cash_amount. There will be two categories like INPATIENT(IP) and OUTPATIENT(OP). Can anyone of you please help me to modify the code in a better manner. And can You please suggest whether Global Temporary tables are better or can we use the tables directly.
    INSERT INTO GTT_PATIENTBILL
    SELECT *
      FROM BILLING.PATIENTBILL P
    WHERE P.LOCATIONID = IN_LOCATIONID
       AND TRUNC(P.BILLDATE) BETWEEN TRUNC(IN_YEARDATE) AND TRUNC(IN_FROMDATE);
    INSERT INTO GTT_PATIENTBILLDETAILS  
    SELECT PB.*
      FROM BILLING.PATIENTBILL P, BILLING.PATIENTBILLDETAILS PB
    WHERE P.LOCATIONID = IN_LOCATIONID
       AND P.BILLNO = PB.BILLNO
       AND TRUNC(P.BILLDATE) BETWEEN TRUNC(IN_YEARDATE) AND TRUNC(IN_FROMDATE);
    INSERT INTO GTT_TRANSACTION
    SELECT *
      FROM BILLING.TRANSACTION T
    WHERE T.LOCATIONID = IN_LOCATIONID
       AND TRUNC(T.CREATEDDATE) BETWEEN TRUNC(IN_YEARDATE) AND
           TRUNC(IN_FROMDATE);
    DELETE FROM TEMP_1;
    INSERT INTO TEMP_1
      SELECT (CASE
               WHEN PARTICULARS IS NULL AND FLG = 1 THEN
                'TOTAL COLLECTIONS'
               WHEN PARTICULARS IS NULL AND FLG = 2 THEN
                'TOTAL DEDUCTIONS'
               ELSE
                PARTICULARS
             END) PARTICULARS,
             SUM(A) "FOR THE DAY",
             SUM(B) "MONTH TO DATE",
             SUM(C) "YEAR TO DATE"
        FROM (SELECT PARTICULARS,
                     SUM(TOTAL_CASH_AMOUNT_DAY) A,
                     SUM(TOTAL_CASH_AMOUNT_MONTH) B,
                     SUM(TOTAL_CASH_AMOUNT_YEAR) C,
                     1 FLG
                FROM (SELECT 'OP CASH' PARTICULARS,
                             SUM(P.TOTALSERVICEAMOUNT) TOTAL_CASH_AMOUNT_DAY,
                             0 TOTAL_CASH_AMOUNT_MONTH,
                             0 TOTAL_CASH_AMOUNT_YEAR
                        FROM GTT_PATIENTBILL P--BILLING.PATIENTBILL P, BILLING.PATIENTBILLDETAILS PB
                       WHERE P.LOCATIONID = IN_LOCATIONID
                         --AND P.BILLNO = PB.BILLNO
                         AND P.BILLINGTYPEID = 1
                         AND P.PATIENTSERVICE = 2
                         AND TRUNC(P.BILLDATE) =TRUNC(IN_FROMDATE)
                      UNION ALL
                      SELECT 'OP CASH' PARTICULARS,
                             0,
                             SUM(P.TOTALSERVICEAMOUNT) TOTAL_CASH_AMOUNT_MONTH,
                             0
                        FROM GTT_PATIENTBILL P--BILLING.PATIENTBILL P, BILLING.PATIENTBILLDETAILS PB
                       WHERE P.LOCATIONID = IN_LOCATIONID
                         --AND P.BILLNO = PB.BILLNO
                         AND P.BILLINGTYPEID = 1
                         AND P.PATIENTSERVICE = 2
                         AND TRUNC(P.BILLDATE) BETWEEN TRUNC(IN_MONTHDATE) AND
                             TRUNC(IN_FROMDATE)
                      UNION ALL
                      SELECT 'OP CASH' PARTICULARS,
                             0,
                             0,
                             SUM(P.TOTALSERVICEAMOUNT) TOTAL_CASH_AMOUNT_YEAR
                        FROM GTT_PATIENTBILL P--BILLING.PATIENTBILL P, BILLING.PATIENTBILLDETAILS PB
                       WHERE P.LOCATIONID = IN_LOCATIONID
                         --AND P.BILLNO = PB.BILLNO
                         AND P.BILLINGTYPEID = 1
                         AND P.PATIENTSERVICE = 2
                         AND TRUNC(P.BILLDATE) BETWEEN TRUNC(IN_YEARDATE) AND
                            TRUNC(IN_FROMDATE)
                      UNION ALL
                      SELECT 'IP CASH' PARTICULARS,
                             SUM(P.TOTALSERVICEAMOUNT) TOTAL_CASH_AMOUNT_DAY,
                             0 TOTAL_CASH_AMOUNT_MONTH,
                             0 TOTAL_CASH_AMOUNT_YEAR
                        FROM GTT_PATIENTBILL P--BILLING.PATIENTBILL P, BILLING.PATIENTBILLDETAILS PB
                       WHERE P.LOCATIONID = IN_LOCATIONID
                         --AND P.BILLNO = PB.BILLNO
                         AND P.BILLINGTYPEID = 1
                         AND P.PATIENTSERVICE = 3
                         AND TRUNC(P.BILLDATE) = TRUNC(IN_FROMDATE)
                      UNION ALL
                      SELECT 'IP CASH' PARTICULARS,
                             0,
                             SUM(P.TOTALSERVICEAMOUNT) TOTAL_CASH_AMOUNT_MONTH,
                             0
                        FROM GTT_PATIENTBILL P--BILLING.PATIENTBILL P, BILLING.PATIENTBILLDETAILS PB
                       WHERE P.LOCATIONID = IN_LOCATIONID
                         --AND P.BILLNO = PB.BILLNO
                         AND P.BILLINGTYPEID = 1
                         AND P.PATIENTSERVICE = 3
                         AND TRUNC(P.BILLDATE)  BETWEEN TRUNC(IN_MONTHDATE) AND
                             TRUNC(IN_FROMDATE)
                      UNION ALL
                      SELECT 'IP CASH' PARTICULARS,
                             0,
                             0,
                             SUM(P.TOTALSERVICEAMOUNT) TOTAL_CASH_AMOUNT_YEAR
                        FROM GTT_PATIENTBILL P--BILLING.PATIENTBILL P, BILLING.PATIENTBILLDETAILS PB
                       WHERE P.LOCATIONID = IN_LOCATIONID
                         --AND P.BILLNO = PB.BILLNO
                         AND P.BILLINGTYPEID = 1
                         AND P.PATIENTSERVICE = 3
                         AND TRUNC(P.BILLDATE) BETWEEN TRUNC(IN_YEARDATE) AND
                             TRUNC(IN_FROMDATE)) T1
               GROUP BY PARTICULARS
               Thanks in advance..

    karthick, This is a part of the code.. If I want to calculate other things. Should I need to modify in the same manner or else in the same query it is possible. For your understanding I am pasting the code of the other part with your code replaced.
    select decode(p.patientservice, 2, 'op cash', 3, 'ip cash') particulars,
           sum(
                   case when trunc(p.billdate) = trunc(in_fromdate) then
                            p.totalserviceamount
                        else 0
                   end
              ) a,
           sum(
                   case when trunc(p.billdate) between trunc(in_monthdate) and trunc(in_fromdate) then
                            p.totalserviceamount
                        else 0
                   end
              ) b,
           sum(
                   case when trunc(p.billdate) between trunc(in_yeardate) and trunc(in_fromdate)
                            p.totalserviceamount
                        else 0
                   end
              ) c
      from billing.patientbill p
    where p.locationid    = in_locationid
       adn p.billingtypeid = 1
       and trunc(p.billdate) between trunc(in_yeardate) and trunc(in_fromdate);
    group
        by decode(p.patientservice, 2, 'op cash', 3, 'ip cash');
        UNION ALL
              -----------------TOTAL_CO_CREDIT_AMOUNT--------------------------
              SELECT PARTICULARS,
                     SUM(TOTAL_CO_CREDIT_AMOUNT_DAY) A,
                     SUM(TOTAL_CO_CREDIT_AMOUNT_MONTH) B,
                     SUM(TOTAL_CO_CREDIT_AMOUNT_YEAR) C,
                     1 FLG
                FROM (SELECT 'OP CO CREDIT AMOUNT' PARTICULARS,
                             SUM(P.TOTALSERVICEAMOUNT - P.PATIENTPAIDAMOUNT) TOTAL_CO_CREDIT_AMOUNT_DAY,
                             0 TOTAL_CO_CREDIT_AMOUNT_MONTH,
                             0 TOTAL_CO_CREDIT_AMOUNT_YEAR
                        FROM GTT_PATIENTBILL P
                       WHERE P.LOCATIONID = IN_LOCATIONID
                         AND P.BILLINGTYPEID = 2
                         AND P.DELFLAG=1
                         AND P.PATIENTSERVICE = 2
                         AND TRUNC(P.BILLDATE) = TRUNC(IN_FROMDATE)
                         AND P.PATIENTPAIDAMOUNT <> 0
                      UNION ALL
                      SELECT 'OP CO CREDIT AMOUNT' PARTICULARS,
                             0,
                             SUM(P.TOTALSERVICEAMOUNT - P.PATIENTPAIDAMOUNT) TOTAL_CO_CREDIT_AMOUNT_MONTH,
                             0
                        FROM GTT_PATIENTBILL P
                       WHERE P.LOCATIONID = IN_LOCATIONID
                         AND P.BILLINGTYPEID = 2
                         AND P.DELFLAG=1
                         AND P.PATIENTSERVICE = 2
                         AND TRUNC(P.BILLDATE) BETWEEN TRUNC(IN_MONTHDATE) AND
                             TRUNC(IN_FROMDATE)
                         AND P.PATIENTPAIDAMOUNT <> 0
                      UNION ALL
                      SELECT 'OP CO CREDIT AMOUNT' PARTICULARS,
                             0,
                             0,
                             SUM(P.TOTALSERVICEAMOUNT - P.PATIENTPAIDAMOUNT) TOTAL_CO_CREDIT_AMOUNT_YEAR
                        FROM GTT_PATIENTBILL P
                       WHERE P.LOCATIONID = IN_LOCATIONID
                         AND P.BILLINGTYPEID = 2
                         AND P.DELFLAG=1
                         AND P.PATIENTSERVICE = 2
                         AND TRUNC(P.BILLDATE) BETWEEN TRUNC(IN_YEARDATE) AND
                             TRUNC(IN_FROMDATE)
                         AND P.PATIENTPAIDAMOUNT <> 0
                      UNION ALL
                      SELECT 'IP CO CREDIT AMOUNT' PARTICULARS,
                             SUM(P.TOTALSERVICEAMOUNT - P.PATIENTPAIDAMOUNT) TOTAL_CO_CREDIT_AMOUNT_DAY,
                             0 TOTAL_CO_CREDIT_AMOUNT_MONTH,
                             0 TOTAL_CO_CREDIT_AMOUNT_YEAR
                        FROM GTT_PATIENTBILL P
                       WHERE P.LOCATIONID = IN_LOCATIONID
                         AND P.BILLINGTYPEID = 2
                         AND P.DELFLAG=1
                         AND P.PATIENTSERVICE = 3
                         AND TRUNC(P.BILLDATE) = TRUNC(IN_FROMDATE)
                         AND P.PATIENTPAIDAMOUNT <> 0
                      UNION ALL
                      SELECT 'IP CO CREDIT AMOUNT' PARTICULARS,
                             0,
                             SUM(P.TOTALSERVICEAMOUNT - P.PATIENTPAIDAMOUNT) TOTAL_CO_CREDIT_AMOUNT_MONTH,
                             0
                        FROM GTT_PATIENTBILL P
                       WHERE P.LOCATIONID = IN_LOCATIONID
                         AND P.BILLINGTYPEID = 2
                         AND P.DELFLAG=1
                         AND P.PATIENTSERVICE = 3
                         AND TRUNC(P.BILLDATE) BETWEEN TRUNC(IN_MONTHDATE) AND
                             TRUNC(IN_FROMDATE)
                         AND P.PATIENTPAIDAMOUNT <> 0
                      UNION ALL
                      SELECT 'IP CO CREDIT AMOUNT' PARTICULARS,
                             0,
                             0,
                             SUM(P.TOTALSERVICEAMOUNT - P.PATIENTPAIDAMOUNT) TOTAL_CO_CREDIT_AMOUNT_YEAR
                        FROM GTT_PATIENTBILL P
                       WHERE P.LOCATIONID = IN_LOCATIONID
                         AND P.BILLINGTYPEID = 2
                         AND P.DELFLAG=1
                         AND P.PATIENTSERVICE = 3
                         AND TRUNC(P.BILLDATE) BETWEEN TRUNC(IN_YEARDATE) AND
                             TRUNC(IN_FROMDATE)
                         AND P.PATIENTPAIDAMOUNT <> 0) T5
               GROUP BY PARTICULARS
              UNION ALL
       

Maybe you are looking for