Total Per Day SQL Query Format

I have a table called DollarTransactions in a database, which records purchases. The table has the following fields, which you can see by clicking the link to a screenshot:
http://i33.tinypic.com/vs2byd.jpg
I need to write 3 queries:
1) Total revenue for each day in the month of March 2013. Revenue is measured in "cents" field.
2) Revenue by hour for each day in March 2013
3) User ID of the user who spent the most money in December 2012?
I was working on a query for #1 that went like this:
SELECT trunc(createdDate, 'HH') "Hour", sum(cents)
FROM DollarTransactions
WHERE createdDate BETWEEN 2013-03-01 AND 2013-03-31
GROUP BY trunc(createdDate, 'HH')
But I don't know if that's right, and I'm lost on the other queries. Any help would be really appreciated!
Edited by: 1002073 on Apr 23, 2013 8:28 PM

It is not helpful to post table structures hosted at other websites. Many people might not be able to access them due to firewall restrictions.
I think below queries should resolve your problem:
alter session set nls_date_format = 'DD-Mon-YYYY HH24:MI:SS';
with data as
  select 1 userid, to_date('25-Apr-2013 09:00:00', 'DD-Mon-YYYY HH24:MI:SS') dt, 100 amt from dual union all
  select 2,to_date('25-Apr-2013 10:01:00', 'DD-Mon-YYYY HH24:MI:SS') dt, 150 amt from dual union all
  select 3,to_date('25-Apr-2013 10:45:00', 'DD-Mon-YYYY HH24:MI:SS') dt, 200 amt from dual union all
  select 4,to_date('25-Apr-2013 11:00:00', 'DD-Mon-YYYY HH24:MI:SS') dt, 250 amt from dual union all
  select 5,to_date('25-Apr-2013 12:00:00', 'DD-Mon-YYYY HH24:MI:SS') dt, 300 amt from dual union all
  select 6,to_date('25-Apr-2013 15:00:00', 'DD-Mon-YYYY HH24:MI:SS') dt, 350 amt from dual union all
  select 7,to_date('25-Apr-2013 20:00:00', 'DD-Mon-YYYY HH24:MI:SS') dt, 400 amt from dual union all
  select 8,to_date('25-Apr-2013 23:00:00', 'DD-Mon-YYYY HH24:MI:SS') dt, 450 amt from dual
select trunc(dt, 'DD'), sum(amt) sum_by_date
  from data
group by trunc(dt, 'DD');
with data as
  select 1 userid, to_date('25-Apr-2013 09:00:00', 'DD-Mon-YYYY HH24:MI:SS') dt, 100 amt from dual union all
  select 2,to_date('25-Apr-2013 10:01:00', 'DD-Mon-YYYY HH24:MI:SS') dt, 150 amt from dual union all
  select 3,to_date('25-Apr-2013 10:45:00', 'DD-Mon-YYYY HH24:MI:SS') dt, 200 amt from dual union all
  select 4,to_date('25-Apr-2013 11:00:00', 'DD-Mon-YYYY HH24:MI:SS') dt, 250 amt from dual union all
  select 5,to_date('25-Apr-2013 12:00:00', 'DD-Mon-YYYY HH24:MI:SS') dt, 300 amt from dual union all
  select 6,to_date('25-Apr-2013 15:00:00', 'DD-Mon-YYYY HH24:MI:SS') dt, 350 amt from dual union all
  select 7,to_date('25-Apr-2013 20:00:00', 'DD-Mon-YYYY HH24:MI:SS') dt, 400 amt from dual union all
  select 8,to_date('25-Apr-2013 23:00:00', 'DD-Mon-YYYY HH24:MI:SS') dt, 450 amt from dual
select trunc(dt, 'HH'), sum(amt) sum_by_hour
  from data
group by trunc(dt, 'HH')
order by trunc(dt, 'HH');
with data as
  select 1 userid, to_date('25-Apr-2013 09:00:00', 'DD-Mon-YYYY HH24:MI:SS') dt, 100 amt from dual union all
  select 2,to_date('25-Apr-2013 10:01:00', 'DD-Mon-YYYY HH24:MI:SS') dt, 150 amt from dual union all
  select 3,to_date('25-Apr-2013 10:45:00', 'DD-Mon-YYYY HH24:MI:SS') dt, 200 amt from dual union all
  select 4,to_date('25-Apr-2013 11:00:00', 'DD-Mon-YYYY HH24:MI:SS') dt, 250 amt from dual union all
  select 5,to_date('25-Apr-2013 12:00:00', 'DD-Mon-YYYY HH24:MI:SS') dt, 300 amt from dual union all
  select 6,to_date('25-Apr-2013 15:00:00', 'DD-Mon-YYYY HH24:MI:SS') dt, 350 amt from dual union all
  select 7,to_date('25-Apr-2013 20:00:00', 'DD-Mon-YYYY HH24:MI:SS') dt, 400 amt from dual union all
  select 8,to_date('25-Apr-2013 23:00:00', 'DD-Mon-YYYY HH24:MI:SS') dt, 450 amt from dual
select *
  from (
select userid, sum(amt)
  from data
group by userid
order by sum(amt) desc
where rownum = 1;

Similar Messages

  • Oracle BPEL processes per day  -DB query

    Hi all,
    I am trying to produce some statistics for our daily created BPEL processes in the Oracle dehydration store.
    In particular I am running the following query towards the cube_instance table:
    select to_char(creation_date, 'dd-mon-yyyy hh24:mi:ss') as date, count(*) as total
    from cube_instance
    where creation_date >'01-MAR-10'
    group by to_char(creation_date, 'dd-mon-yyyy hh24:mi:ss')
    I know I am not an oracle programmer and I am sure something is wrong with the converion.
    Any help would be appreciated.
    Brgds,
    Loukas

    Thanks James.
    Yoru comments were correct , the query has run but the output is rather not what I wanted to see.
    It gives me as output every single process and of course next to it the total which is obviously 1:
    CREATION_DATE TOTAL
    01-MAR-10 12.55.03.936000000 PM 1
    01-MAR-10 12.55.04.528000000 PM 1
    01-MAR-10 12.55.06.276000000 PM 1
    01-MAR-10 01.16.50.560000000 PM 1
    01-MAR-10 01.16.50.581000000 PM 1
    01-MAR-10 01.16.51.235000000 PM 1
    01-MAR-10 01.18.27.893000000 PM 1
    01-MAR-10 01.18.27.914000000 PM 1
    01-MAR-10 01.18.28.477000000 PM 1
    01-MAR-10 01.26.07.038000000 PM 1
    01-MAR-10 01.26.07.610000000 PM 1
    01-MAR-10 01.26.08.788000000 PM 1
    01-MAR-10 01.32.54.038000000 PM 1
    01-MAR-10 01.32.54.389000000 PM 1
    01-MAR-10 01.32.55.397000000 PM 1
    01-MAR-10 02.10.43.199000000 PM 1
    01-MAR-10 03.14.57.502000000 PM 1
    01-MAR-10 03.15.00.578000000 PM 1
    01-MAR-10 03.15.00.608000000 PM 1
    01-MAR-10 03.15.01.331000000 PM 1
    01-MAR-10 03.18.05.760000000 PM 1
    01-MAR-10 03.18.06.092000000 PM 1
    I would like the sum of the days and the sum of the processes that day. I have searched a lot in other BPEL blogs/sites wbut nothing similar found.
    Thanks,
    Loukas

  • OBIEE SQL Query formate problem

    Hai All,
    i am tring to see viewlog in obiee it is givinn the following formate.
    WITH
    SAWITH0 AS (select sum(T338777.CST) as c1,
    sum(T338777.FINAL_INVOICE_AMT) as c2,
    T66199.X_DISP_FSCL_YEAR as c3,
    T66199.FSCL_MONTH as c4,
    substr(T66199.MONTH_NAME , 1, 3) as c5,
    T37817.NAME as c6,
    T101991.NAME as c7,
    T66199.FSCL_YEAR as c8,
    T101991.ROW_WID as c9
    from
    W_INT_ORG_D T37817,
    W_ORG_D T101991 /* Division (W_ORG_D) */ ,
    W_MONTH_D T66199 /* Generic Month (W_MONTH_D) */ ,
    WC_INVC_SPARES_PO_A T338777 /* Spare PO(WC_INVC_SPARES_PO_A) */
    where ( T37817.ROW_WID = T338777.ORG_WID and T66199.ROW_WID = T338777.MONTH_WID and T66199.X_DISP_FSCL_YEAR = '2010-11' and T101991.ROW_WID = T338777.DIVN_WID and T101991.DIVN_FLG = 'Y' )
    group by T37817.NAME, T66199.FSCL_MONTH, T66199.FSCL_YEAR, T66199.X_DISP_FSCL_YEAR, T101991.NAME, T101991.ROW_WID, substr(T66199.MONTH_NAME , 1, 3))
    I need the  following formate. what should i do?
    select sum(T338777.CST) as c1,
    sum(T338777.FINAL_INVOICE_AMT) as c2,
    T66199.X_DISP_FSCL_YEAR as c3,
    T66199.FSCL_MONTH as c4,
    substr(T66199.MONTH_NAME , 1, 3) as c5,
    T37817.NAME as c6,
    T101991.NAME as c7,
    T66199.FSCL_YEAR as c8,
    T101991.ROW_WID as c9
    from
    W_INT_ORG_D T37817,
    W_ORG_D T101991 /* Division (W_ORG_D) */ ,
    W_MONTH_D T66199 /* Generic Month (W_MONTH_D) */ ,
    WC_INVC_SPARES_PO_A T338777 /* Spare PO(WC_INVC_SPARES_PO_A) */
    where ( T37817.ROW_WID = T338777.ORG_WID and T66199.ROW_WID = T338777.MONTH_WID and T66199.X_DISP_FSCL_YEAR = '2010-11' and T101991.ROW_WID = T338777.DIVN_WID and T101991.DIVN_FLG = 'Y' )
    group by T37817.NAME, T66199.FSCL_MONTH, T66199.FSCL_YEAR, T66199.X_DISP_FSCL_YEAR, T101991.NAME, T101991.ROW_WID, substr(T66199.MONTH_NAME , 1, 3))
    Regards,
    Ram

    Hi,
    You messed up with database features in OBIEE rpd. Check the below link
    http://gerardnico.com/wiki/dat/obiee/vertical_fragmentation_sql
    Regards,
    Sandeep

  • Need some help over sql query format

    Input :
    TABLE 1 ppl
    id name
    1 ravi
    2 andy
    3 john
    TABLE 2 fa_ppl
    id attr_name attr_value
    1 watch Guess
    1 laptop Sony
    2 fashion casual
    2 laptop Dell
    3 watch fossil
    3 fashion formal
    OUTPUT Required:(3 rows)
    name watch laptop fashion
    ravi guess sony NULL
    andy NULL dell casual
    john fossil NULL formal
    SQL Statements that may help in schema objects:
    create table ppl(id number,name varchar2(50));
    create table fa_ppl(id number,attr_name varchar2(20), attr_value varchar2(20));
    insert into ppl values(1,'ravi');
    insert into ppl values(2,'andy');
    insert into ppl values(3,'john');
    insert into fa_ppl values(1,'laptop','sony');
    insert into fa_ppl values(1,'watch','guess');
    insert into fa_ppl values(2,'laptop','dell');
    insert into fa_ppl values(2,'fashion','casual');
    insert into fa_ppl values(3,'fashion','formal');
    insert into fa_ppl values(3,'watch','fossil');
    I tried in the below way:
    Select P.name,
    case when attr_name='fashion' then attr_value end as fashion ,
    case when attr_name='laptop' then attr_value end as laptop,
    case when attr_name='watch' then attr_value end as watch,
    from ppl P join fa_ppl F on (P.id=F.id and F.attr_name in ('fashion','laptop','watch'))
    PROBLEM:
    Getting separate rows(6 rows in my case) for each attribute_value.
    Thanks a lot.....

    What you are trying is a pivot. There is a [url https://forums.oracle.com/forums/thread.jspa?threadID=2174552#9360005]thread in the FAQ linking to various methods.
    You are actually pretty close, if you just do a group by on your select:
    Select P.name,
    max(case when attr_name='fashion' then attr_value end) as fashion ,
    max(case when attr_name='laptop' then attr_value end) as laptop,
    max(case when attr_name='watch' then attr_value end) as watch
    from ppl P join fa_ppl F on (P.id=F.id and F.attr_name in ('fashion','laptop','watch'))
    group by
    p.nameBut if you have several people with same name, you probably want to do this:
    Select
    p.id, /*you may omit this column if you do not need it*/
    max(P.name) as name,
    max(case when attr_name='fashion' then attr_value end) as fashion ,
    max(case when attr_name='laptop' then attr_value end) as laptop,
    max(case when attr_name='watch' then attr_value end) as watch
    from ppl P join fa_ppl F on (P.id=F.id and F.attr_name in ('fashion','laptop','watch'))
    group by
    p.idSimilar can be done in 11G with the PIVOT statement. See the links in the FAQ thread.

  • Sql query format involving a funtion that returns multiple/array of values

    Lets say u have two types of functions...
    FUNCTION 1
    function my_name ---- in package spec
         return varchar2;
    function my_name -----in package body
    return varchar2
    is
    begin
    return 'this is my name';
    end my_name;
    select package.my_name from dual; -- get the output as "this is my name"
    ====================================
    FUNCTION 2
    Type my_table is table of varchar2(25);
    function my_phone_numbers
    return package.my_table;
    function my_phone_numbers return package.my_table
    is
    mt package.my_table:= package.my_table('0000-000-0000','111-111-1111');
    begin
    return mt;
    end my_phone_numbers;
    select package.my_phone_numbers from dual; --- output errors -- looks like the syntax is wrong
    please help...thanks

    Oh you are right. I thought the OP had the types in place. Here is the correct one:
    SQL> create type my_table is table of varchar2(25);
      2  /
    Type created.
      1  create or replace function my_phone_numbers
      2  return my_table
      3  is
      4  mt my_table:= my_table('0000-000-0000','111-111-1111');
      5  begin
      6  return mt;
      7* end my_phone_numbers;
    SQL> /
    Function created.
    SQL> select * from table(my_phone_numbers);
    COLUMN_VALUE
    0000-000-0000
    111-111-1111
    No (user defined) sql types and no pipelined function.
    User defined types are needed for this to work, but it works without pipelined functions either.
    Message was edited by:
    Yas

  • SQL Query - The number of columns specified in "SQL Query" does not match t

    I am creating new UDM for tablespace alert, below is my query,however its failing with error
    SQL Query - The number of columns specified in "SQL Query" does not match the value specified in "SQL Query Output"
    I selected Metric type is number
    SQL Query Format : Two columns
    Query:
    SELECT d.tablespace_name,round(((a.bytes - NVL(f.bytes,0))*100/a.maxbytes),2)
    used_pct FROM sys.dba_tablespaces d,(select tablespace_name, sum(bytes) bytes, sum(greatest(maxbytes,bytes)) maxbytes from sys.dba_data_files group by tablespace_name) a,(select tablespace_name, sum(bytes) bytes from sys.dba_free_space group by tablespace_name) f
    WHERE d.tablespace_name = a.tablespace_name(+) AND d.tablespace_name = f.tablespace_name(+)
    AND NOT (d.extent_management = 'LOCAL' AND d.contents = 'TEMPORARY');
    Any clues why i am getting error.

    SQL> SELECT d.tablespace_name,round(((a.bytes - NVL(f.bytes,0))*100/a.maxbytes),2) used_pct
    2 FROM sys.dba_tablespaces d,(select tablespace_name, sum(bytes) bytes, sum(greatest(maxbytes,bytes)) maxbytes from sys.dba_data_files group by tablespace_name) a,(select tablespace_name, sum(bytes) bytes from sys.dba_free_space group by tablespace_name) f
    3 WHERE d.tablespace_name = a.tablespace_name(+) AND d.tablespace_name = f.tablespace_name(+)
    4 AND NOT (d.extent_management = 'LOCAL' AND d.contents = 'TEMPORARY');
    TABLESPACE_NAME USED_PCT
    MGMT_TABLESPACE .82
    SYSAUX 1.52
    UNDOTBS1 .32
    RMAN .02
    CORRUPT_TS 10.63
    USERS 0
    SYSTEM 2.26
    MGMT_ECM_DEPOT_TS .04
    MGMT_AD4J_TS 0

  • Any SQL Query Site.?

    Hello Gurus,
    Are there any good SQL Queries related site, which can help me to build me SQL Query formation strong?
    Thanx in advance,
    Pritam.

    Do searches on OTN, keep accessing different topics
    in OTN , u can also check following links....
    http://asktom.oracle.com
    http://sqlcourse.com/
    Regards,
    Srini

  • SQL query against ConfigMgr DB causing 100% cpu usage on SQL server throughout day

    Hi, I am hoping someone here may have an idea of what I can do to resolve this as I am not much of a SQL guy. Here is what I know. Throughout the day, monday-friday, my ConfigMgr SQL server sits at 98-100% processor usage.
    Using the following query I have narrowed down the culprit of the high cpu usage throughout the day:
    SELECT p.spid, p.status, p.hostname, p.loginame, p.cpu, r.start_time, r.command,
    p.program_name, text
    FROM sys.dm_exec_requests AS r,
    master.dbo.sysprocesses AS p
    CROSS APPLY sys.dm_exec_sql_text(p.sql_handle)
    WHERE p.status NOT IN ('sleeping', 'background')
    AND r.session_id = p.spid
    Even though my knowledge of SQL is light, I believe the following output clearly defines the thread responsible for the high cpu usage. This "program_name" is present throughout the day and as long as its there, cpu usage remains at or near 100%:
    The text output of the above culprit is as follows (sorry this is long):
    -- Name : spDrsSummarizeSendHistory
    -- Definition : SqlObjs
    -- Scope : CAS_OR_PRIMARY_OR_SECONDARY
    -- Object : P
    -- Dependencies : <Detect>
    -- Description : Summarize DrsSendHistory information into DrsSendHistorySummary
    CREATE PROCEDURE spDrsSummarizeSendHistory
    AS
    BEGIN
    SET NOCOUNT ON;
    DECLARE @CurrentTime DateTime;
    DECLARE @SiteCode nvarchar(3);
    DECLARE @LastSummarizationTime DateTime;
    DECLARE @NextSummarizationTime DateTime;
    DECLARE @Interval INT; -- summarize interval in minutes
    DECLARE @ReplicationID INT
    DECLARE @iMaxID INT
    DECLARE @iCurrentID INT
    DECLARE @iBatchSize INT = 50
    DECLARE @ReplicationPattern NVARCHAR(255)
    DECLARE @TargetSite NVARCHAR(3);
    DECLARE @TimeTable TABLE (TargetSite NVARCHAR(3), StartTime DATETIME, EndTime DATETIME, PRIMARY KEY (TargetSite, StartTime, EndTime))
    DECLARE @TargetSites TABLE (SiteCode NVARCHAR(3) PRIMARY KEY)
    DECLARE @ChildTargetSites TABLE (TargetSite NVARCHAR(3), LastSummarizationTime DATETIME, [Interval] INT, PRIMARY KEY (TargetSite))
    DECLARE @ReplicationGroup TABLE (ID INT, ReplicationPattern NVARCHAR(255))
    IF OBJECT_ID(N'TempDB..#DrsSendHistorySummary') IS NOT NULL
    DROP TABLE #DrsSendHistorySummary
    CREATE TABLE #DrsSendHistorySummary (ID BIGINT IDENTITY(1, 1) NOT NULL, SourceSite NVARCHAR(3), TargetSite NVARCHAR(3), ReplicationGroupID INT, SyncDataSize BIGINT, CompressedSize BIGINT, UnCompressedSize BIGINT, MessageCount INT, ChangeCount INT, SummarizationTime DATETIME, PRIMARY KEY (ID))
    SET @CurrentTime = GETUTCDATE();
    SET @SiteCode = dbo.fnGetSiteCode();
    INSERT INTO @ReplicationGroup (ID, ReplicationPattern)
    SELECT RD.ID, RD.ReplicationPattern
    FROM ReplicationData RD
    WHILE EXISTS (SELECT * FROM @ReplicationGroup)
    BEGIN
    SELECT TOP (1) @ReplicationID = ID, @ReplicationPattern = ReplicationPattern FROM @ReplicationGroup
    TRUNCATE TABLE #DrsSendHistorySummary
    IF (((@ReplicationPattern = N'global' OR @ReplicationPattern=N'site') AND dbo.fnIsPrimary() = 1)
    OR (@ReplicationPattern = N'global_proxy' AND dbo.fnIsSecondary() = 1))
    BEGIN -- when current site is child
    SET @LastSummarizationTime = ISNULL(( SELECT MAX(SummarizationTime) FROM DrsSendHistorySummary WHERE SourceSite = @SiteCode AND ReplicationGroupID = @ReplicationID),
    (SELECT MIN(EndTime) FROM DrsSendHistory WHERE ReplicationGroupID = @ReplicationID) );
    SET @Interval = ISNULL((SELECT VALUE FROM RCMSQLCONTROLPROPERTY SCP, RCMSQLCONTROL SC
    WHERE SCP.ControlID = SC.ID AND SCP.Name = N'Send History Summarize Interval' AND SC.TypeID = 3 and SC.SiteNumber = dbo.fnGetSiteNumber()), 15); -- default 15 minutes
    DELETE @TargetSites
    INSERT INTO @TargetSites (SiteCode)
    SELECT DISTINCT SiteCode FROM DRS_MessageActivity_Send WHERE ReplicationID = @ReplicationID
    IF @LastSummarizationTime IS NOT NULL AND EXISTS (SELECT * FROM @TargetSites)
    BEGIN
    SET @NextSummarizationTime = DATEADD( minute, DATEDIFF(minute, 0, @LastSummarizationTime)/@Interval *@Interval + @Interval, 0);
    -- Summarized according to interval
    DELETE @TimeTable
    WHILE (@CurrentTime >= @NextSummarizationTime )
    BEGIN
    INSERT INTO @TimeTable (TargetSite, StartTime, EndTime)
    SELECT SiteCode, @LastSummarizationTime, @NextSummarizationTime FROM @TargetSites
    SET @LastSummarizationTime = @NextSummarizationTime;
    SET @NextSummarizationTime = DATEADD(mi, @Interval, @NextSummarizationTime );
    END
    INSERT INTO #DrsSendHistorySummary (SourceSite, TargetSite, ReplicationGroupID, SyncDataSize, CompressedSize, UnCompressedSize, MessageCount, ChangeCount, SummarizationTime)
    SELECT @SiteCode, T.TargetSite, @ReplicationID, SUM(ISNULL(D.SyncDataSize, 0)), SUM(ISNULL(D.CompressedSize, 0)), SUM(ISNULL(D.UnCompressedSize, 0)), SUM(ISNULL(D.MessageCount, 0)), SUM(ISNULL(ChangeCount, 0)), T.EndTime
    FROM DrsSendHistory D RIGHT JOIN @TimeTable T ON D.EndTime >= T.StartTime AND D.EndTime < T.EndTime AND ReplicationGroupID = @ReplicationID AND T.TargetSite = D.TargetSite
    GROUP BY T.TargetSite, T.StartTime, T.EndTime;
    END
    END
    ELSE IF ((@ReplicationPattern = N'global' AND dbo.fnIsCAS() = 1)
    OR (@ReplicationPattern = N'global_proxy' AND dbo.fnIsPrimary() = 1))
    BEGIN -- when current site is parent
    DELETE @ChildTargetSites
    INSERT INTO @ChildTargetSites(TargetSite, LastSummarizationTime, [Interval])
    SELECT DISTINCT(DSH.SiteCode),
    ISNULL(( SELECT MAX(SummarizationTime) FROM DrsSendHistorySummary WHERE SourceSite = @SiteCode AND ReplicationGroupID = @ReplicationID AND TargetSite=DSH.SiteCode),
    (SELECT MIN(EndTime) FROM DrsSendHistory WHERE ReplicationGroupID = @ReplicationID) ) AS LastSummarizeTime,
    ISNULL((SELECT VALUE FROM RCMSQLCONTROLPROPERTY SCP, RCMSQLCONTROL SC WHERE SCP.ControlID = SC.ID AND SCP.Name = N'Send History Summarize Interval' AND SC.TypeID = 3 and SC.SiteNumber = dbo.fnGetSiteNumberBySiteCode(DSH.SiteCode)), 15) AS Interval
    FROM DRS_MessageActivity_Send DSH WHERE DSH.ReplicationID = @ReplicationID
    GROUP BY DSH.SiteCode;
    DELETE @TimeTable
    WHILE EXISTS (SELECT * FROM @ChildTargetSites)
    BEGIN
    SELECT TOP (1) @TargetSite = TargetSite, @LastSummarizationTime = LastSummarizationTime, @Interval = Interval FROM @ChildTargetSites
    SET @NextSummarizationTime = DATEADD( minute, DATEDIFF(minute, 0, @LastSummarizationTime)/@Interval *@Interval + @Interval, 0);
    -- Summarized according to interval
    WHILE (@CurrentTime >= @NextSummarizationTime )
    BEGIN
    INSERT INTO @TimeTable (TargetSite, StartTime, EndTime)
    SELECT @TargetSite, @LastSummarizationTime, @NextSummarizationTime
    SET @LastSummarizationTime = @NextSummarizationTime;
    SET @NextSummarizationTime = DATEADD(mi, @Interval, @NextSummarizationTime );
    END
    DELETE @ChildTargetSites WHERE TargetSite = @TargetSite
    END;
    INSERT INTO #DrsSendHistorySummary (SourceSite, TargetSite, ReplicationGroupID, SyncDataSize, CompressedSize, UnCompressedSize, MessageCount, ChangeCount, SummarizationTime)
    SELECT @SiteCode, T.TargetSite, @ReplicationID, SUM(ISNULL(D.SyncDataSize, 0)), SUM(ISNULL(D.CompressedSize, 0)), SUM(ISNULL(D.UnCompressedSize, 0)), SUM(ISNULL(D.MessageCount, 0)), SUM(ISNULL(D.ChangeCount, 0)), @NextSummarizationTime
    FROM DrsSendHistory D RIGHT JOIN @TimeTable T ON D.EndTime >= T.StartTime AND D.EndTime < T.EndTime AND ReplicationGroupID = @ReplicationID AND T.TargetSite = D.TargetSite
    GROUP BY T.TargetSite, T.StartTime, T.EndTime;
    END;
    SELECT @iMaxID = MAX(ID), @iCurrentID = 0 FROM #DrsSendHistorySummary
    -- BATCH INSERT TO REAL TABLE
    WHILE (@iCurrentID < @iMaxID)
    BEGIN
    INSERT INTO DrsSendHistorySummary (SourceSite, TargetSite, ReplicationGroupID, SyncDataSize, MessageCount, ChangeCount, SummarizationTime)
    SELECT SourceSite, TargetSite, ReplicationGroupID, SyncDataSize, MessageCount, ChangeCount, SummarizationTime
    FROM #DrsSendHistorySummary WHERE ID > @iCurrentID AND ID <= (@iCurrentID + @iBatchSize)
    SET @iCurrentID = @iCurrentID + @iBatchSize
    END
    TRUNCATE TABLE #DrsSendHistorySummary
    DELETE @ReplicationGroup WHERE ID = @ReplicationID
    END
    END
    If anyone has any experience with this issue or anything similar and might be able to point me in the right direction, any responses would be greatly appreciated. Thanks for reading!

    Normally, this summary job every few mins which only summarize last few mins sending history. If the job was not running for long time, the first time, this sproc will summarize a lot more data than normal. So it could fail which will make things worse and
    worse over time.
    If sending summary data is not a big concern here, you can manually insert a dummy row with most recent time as Summarizationtime, so that, when summary job kicks in next time, it will only summary short interval data.
    DrsSendHistory is that the table records every sending on every group. This table is one of the key of replication logic. For your environment, on primary site, it could have up to 24(hrs) * 60 (mins) / 2 (sync interval) * 36(secondary sites) records per
    day for Secondary_Site_Replication_Configuration group and 24 * 60 / 5 * 22 records for Secondary Site Data.
    Umair Khan | http://blogs.technet.com/umairkhan
    Hi Umair,
    Thank you for the reply. My plan was to go ahead with your suggestions but what I tried first was to get my VM guy to give the SQL server access to more CPU resources. We had already configured it with what would have seemed to be plenty, as per Microsoft's
    sizing requirements, but I figured it couldn't hurt to rule out - he gave the SQL server access to a huge portion of the host processing power and since then CPU usage on the server has NOT been an issue.
    It would appear that the large amounts of secondary sites we have just simply put a lot of stress on the SQL server with out of the box replication settings. Since the entire VM host is for System Center only, and our other System Center servers are using
    very little resources, this solution has ended up being valid.
    Thanks again for everyone's help with this.

  • Query for seeing the amount of archive switchs per day

    Hi
    I want a query for seeing the amount of archive switchs per day.
    Example:
    date & amount
    17/01/2009 40
    18/01/2009 33
    19/01/2009 45
    Thanks

    Hi friend Jamsher
    I tested in a RAC database and the result is null....
    SQL> SELECT ROUND(AVG(1440 * (b.first_time - a.first_time)), 0) "Log switch
    2 time - minutes"
    3 FROM v$loghist a, v$log b
    4 WHERE b.sequence# = a.sequence# + 1
    5 AND a.sequence# = (SELECT MAX(sequence#) FROM v$loghist)
    6 ORDER BY a.sequence#;
    Log switch
    time - minutes
    SQL>
    Thanks

  • Sql query to get number of days monthwise

    Hi,
    i am new to sql, can anyone please tell me query to find number of working days between two dates month wise.
    say
    firstdate last date
    21/03/2011 25/06/2011
    march april may june
    9 22 23 18

    Hi,
    918373 wrote:
    even a result like,
    stud_id month amount
    1234 MAR-11 xyz
    1234 JUL-11 ...Please post the exact output that you want.
    Do you want 'xyz' in the output, or do you want a number like 42 (2 hours * 6 weekdays in March 2011, plus 5 hpours * 6 weekdays = 12 + 30 = 42)?
    If you want 42, then post 42. Spend 5 minutes (if it comes to that much) with a calendar and a calculator to get the exact results you want.
    >
    >
    is much better,
    in that case i want it as a view, so that i can get further details from the view....Substituting your table and column names, into the query I posted earlier and replacing COUNT (*) with SUM (no_of_hours), the query is
    WITH     cntr     AS
         SELECT     LEVEL - 1     AS n
         FROM     (
                  SELECT  MAX (enddate - startdate)     AS days_in_range
                  FROM    class_dets
         CONNECT BY     LEVEL     <= 1 + days_in_range
    SELECT       x.stud_id
    ,       TO_CHAR ( TRUNC (x.startdate + c.n, 'MONTH')
                , 'fmMonth YYYY'
                )               AS month
    ,       SUM (no_of_hours)          AS total_hours
    FROM       class_dets  x
    JOIN       cntr        c  ON   x.enddate >= x.startdate + c.n
    WHERE       TO_CHAR ( x.startdate + c.n
                  , 'DY'
                , 'NLS_DATE_LANGUAGE=ENGLISH'     -- If necessary
                )      NOT IN ('SAT', 'SUN')
    GROUP BY  x.stud_id
    ,            TRUNC (x.startdate + c.n, 'MONTH')
    ORDER BY  x.stud_id
    ,            TRUNC (x.startdate + c.n, 'MONTH')
    ;The output, with the sample data you posted, is:
    `  STUD_ID MONTH                                     TOTAL_HOURS
          1234 March 2011                                         42
          1234 April 2011                                        147
          1234 May 2011                                          154
          1234 June 2011                                         154
          1234 July 2011                                          72
          1234 August 2011                                        46
          1234 September 2011                                     14
          1235 June 2011                                          36
          1235 July 2011                                          84
          1235 August 2011                                        92
          1235 September 2011                                     88
          1235 October 2011                                       12
          1236 June 2012                                          56
          1236 July 2012                                         154
          1236 August 2012                                        14Aside from pivoting, is that what you want?
    i edited the your query,
    WITH     all_dates     AS
         SELECT     start_date + LEVEL - 1     AS a_date
         FROM     (
                   SELECT     TO_DATE ((select startdate from class_dets where stud_id=1236), 'DD/MM/YYYY')     AS start_date
                   ,     TO_DATE ((select enddate from class_dets where stud_id=1236), 'DD/MM/YYYY')     AS end_dateInstead of the 2 lines above, the query I posted had
    SELECT  MAX (enddate - startdate)     AS days_in_rangeWhy did you make that change?
    The first argument to TO_DATE is supposed to be a string. You're calling TO_DATE with this as the first argument
    (select startdate from class_dets where stud_id=1236)which is a DATE, not a string.
                   FROM     dual
         CONNECT BY     LEVEL     <= end_date + 1 - start_date
    SELECT     TO_CHAR ( TRUNC (a_date, 'MONTH')
              , 'fmMonth YYYY'
              )               AS month
    ,     COUNT (*) * (select fee from class_dets where stud_id=1236) * (select no_of_hours from class_dets where stud_id=1236)               AS amount
    FROM     all_dates
    WHERE     a_date - TRUNC (a_date, 'IW')     < 5
    GROUP BY TRUNC (a_date, 'MONTH')
    ORDER BY TRUNC (a_date, 'MONTH')
    it works very well, but instead of specifying stud_id as 1236,
    but when i say,
    WITH     all_dates     AS
         SELECT     start_date + LEVEL - 1     AS a_date
         FROM     (
                   SELECT     TO_DATE ((select startdate from class_dets where stud_id=cd.stu_id), 'DD/MM/YYYY')     AS start_date
                   ,     TO_DATE ((select enddate from class_dets where stud_id=cd.stud_id), 'DD/MM/YYYY')     AS end_date
                   FROM     dual
         CONNECT BY     LEVEL     <= end_date + 1 - start_date
    SELECT     cd.stud_id,TO_CHAR ( TRUNC (a_date, 'MONTH')
              , 'fmMonth YYYY'
              )               AS month
    , count(*)
    ,     COUNT (*) * (select fee from class_dets where stud_id=1236) * (select no_of_hours from class_dets where stud_id=1236)               AS amount
    FROM     all_dates,class_dets cd
    WHERE     a_date - TRUNC (a_date, 'IW')     < 5
    GROUP BY TRUNC (a_date, 'MONTH'),cd.stud_id
    ORDER BY TRUNC (a_date, 'MONTH'),cd.stud_id
    i get error
                   SELECT     TO_DATE ((select startdate from class_dets where stud_id=cd.stu_id), 'DD/MM/YYYY')     AS start_date
    ERROR at line 6:
    ORA-00904: "CD"."STU_ID": invalid identifierThere's no column called stu_id in class_dets. There is a column called stud_id (with 2 'd's).
    >
    what should i do?
    (sorry about the query format...how display query in a formatted way? )This site noramlly compresses whitespace.
    Whenever you post formatted text (including, but not limited to, code) on this site, type these 6 characters:
    \(small letters only, inside curly brackets) before and after each section of formatted text, to preserve spacing.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Report from SQL Query -Excel format only show the first page

    Hi,
    I have some Reports from SQL Query. In the display options, I choose Excel as default format. The Excel documents only show the first page. If I choose HTML as default format, it shows every rows.
    Please advise on how to have a complete Excel document as HTML format does.
    Thanks a lot.
    Lina Han

    I beleive when you export Oracle reports to Excel it is the Data that is transferred along with Column Names.
    You cannot export the variables defined on the report.
    Hence you will not be able to export the Footer to excel. (Still looking into it will let you know if i find anything interesting)
    Regards,
    Bhushan Salgar

  • Can we generate the output of SQL Query in XML format ..

    Hi Team,
    Can we generate an XML doc for an SQL Query.
    I've seen in SQL Server 2000.It is generating the output of an SQL Query in xml format.
    select * from emp for xml auto
    The output looks like
    <emp EMPNO="7369" ENAME="SMITH" JOB="CLERK" MGR="7902" HIREDATE="1980-12-17T00:00:00" SAL="2800" DEPTNO="20"/><emp EMPNO="7370" ENAME="SMITH" JOB="CLERK" MGR="7902" HIREDATE="1980-12-17T00:00:00" SAL="2800" DEPTNO="10"/>

    Just a little bit of short hand.
    Get the XML out of your database, via HTTP
    Of course the easiest method is just to return an XMLType from a stored procedure and let the calling routine figure out what to do with it. Instead
    of that way though, I'll show you how to do it via HTTP. It's all completely built into 10g and is super easy to use.
    CREATE OR REPLACE VIEW emps_and_depts AS
    SELECT e.employee_id AS "EmployeeId",
    e.last_name AS "Name",
    e.job_id AS "Job",
    e.manager_id AS "Manager",
    e.hire_date AS "HireDate",
    e.salary AS "Salary",
    e.commission_pct AS "Commission",
    XMLFOREST (
    d.department_id AS "DeptNo",
    d.department_name AS "DeptName",
    d.location_id AS "Location"
    ) AS "Dept"
    FROM employees e, departments d
    WHERE e.department_id = d.department_id
    Some people hear web and immediately start salivating about security issues. Let me address that quickly. Just because you have the HTTP and/or
    FTP servers running in the database, that does not mean you have a security problem. For one, I would hope your databases are behind a firewall.
    Second, with the correct architecture (DMZ, app servers, etc) you can make this data available outside the firewall fairly transparently and third,
    just because it's on the web does not mean the data MUST be available on the internet. This is a good way to make your data available on your
    intranet. If you are worried about people INSIDE your firewall, that still doesn't preclude web based access. Follow Oracle security guidelines.
    Before I show you how to get to your data, let's talk about URLs and URIs. A URL is a Uniform Resource Locater and URI is a Uniform Resource
    Identifier. A URL is the way you would identify a document on the net, i.e. http://www.oracle.com is a URL. A URI is a more generic form of a URL.
    Oracle supports three types of URI: HTTPURIType - basically a URL (which would be like the URL above), XDURIType - a pointer to an XDB resource
    (usually an XML document but can be other objects), and DBURIType - a pointer to database objects.
    It's the DBURIType that we're going to concentrate on here. The DBURIType let's us reference database objects using a file/folder paradigm. The
    format for a DBURI is /oradb/<schema>/<table>. Oradb is shorthand for the database; it is not the database name or SID. My database is named XE
    but I still use oradb in the DBURI. For example, the view we created above is in my XE database, is owned by HR (at least in my case) and is called
    EMPS_AND_DEPTS. This can be referenced as /oradb/HR/EMPS_AND_DEPTS.
    If the view had many rows and you wanted only one of them, you can restrict it by including a predicate. The documentation for XDB has a great
    write up on Using DBURIs.In our case, we are going to write out the entire document. Now that you understand that the DBURI is a pointer to
    objects in our instance, we can use that to access the data as a URL.
    The format for the URL call is http://<machinename>:<port>/<DBURI>
    In my case, my XE database is running on a machine called mach1 and is listening on port 8080. So to see the view we created above, I open my
    browser and navigate to: http//mach1:8080/oradb/HR/EMPS_AND_DEPTS
    The created URL will be as http//mach1:8080/oradb/PUBLIC/EMPS_AND_DEPTS
    If your database is set up correctly and listening on port 8080 (the default), your browser should ask you to login. Login as the user who created the
    view (in my case HR). You should now get an XML document displayed in your browser.
    And that's it. It doesn't get much simpler than that. If you get rid of the descriptive text above, it basically comes down to:
    Create a table or view
    Open your web browser
    Enter a URL
    Enter a user ID and password
    View your XML
    If you notice, Oracle formatted the data as XML for us. Our view returns scalar columns and an XML fragment called Dept. Oracle formatted the
    return results into an XML format.
    And as a side note, if you look closely, you'll see that my URL has PUBLIC where I said to put HR. PUBLIC is a synonym for all objects that your
    logged in user can see. That way, if your user has been granted select access on many schemas, you can use PUBLIC and see any of them.

  • SQL query, function or SP for converting varbinary to image(.jpg format).

    Dear Sir/Mam
    I want SQL query, function or SP which converts binary data to image (.jpg format).
    I m able to convert image (.jpg format) to varbinary. But not able to convert vice versa.
    thanks in advance.

    Binary data is binary data - "image" is only an intrepretation of binary data.  Therefore your question makes little sense in the context of sql server since it does not have any facilities to utilize images.  Since you provide no context, I'm
    guessing that you are trying to retrieve an image stored in the database in a varbinary column and have your application use it as an image.  If so, you should post your question to a forum that is specific to your development environment.  

  • Adhoc query - Total payroll day issue on infotype 2001

    Dear Expert,
    I am working on the adhoc query and would like to generate the total number of payroll days taken by a particular employee.
    E.g. Employee A has 4 leave record in Nov 2011
    14-Nov, 16, Nov, 23 Nov, 25 Nov
    When I select the reporting period between 1-Nov-2011 to 30-Nov-2011, the total payroll days generated by the adhoc query is only 1. I am not sure why. Please help
    Best Regards,
    WF

    Hi,
    Might be remaining days are Non working days/Weekly offs/ Holidays falls..
    You Better Check through PA30 Overview of Absence records, Whether the Days are deducted from Quota or not.
    Need to check absence class in V_554s_0

  • Date format in PL/SQL Procuredure returning SQL Query

    We have parameters (a begin date and end date) that are entered in on a form and then passed as parameters to a report that is displayed using PL/SQL Procedure returning SQL Query. We would like the users to be able to enter the date in the format of mm/dd/yyyy but when we change the format mask on the begin and end date fields we get invalid month entered. I then went into my PL/SQL procedure and changed the code to the following
    q := q || ' WHERE ' ||
    '(:P41_W_BEGIN_DT IS NULL OR (:P41_W_BEGIN_DT IS NOT NULL AND
    :P41_W_BEGIN_DT <= to_char(HARDWARE_INFO.WARRANTY_END_DT,''mm/dd/yyyy')))
    AND
    (:P41_W_END_DT IS NULL OR (:P41_W_END_DT IS NOT NULL AND :P41_W_END_DT >=
    to_char(HARDWARE_INFO.WARRANTY_END_DT,''mm/dd/yyyy''))
    The code is accepted but when we run the report against the parameters it seems to only be looking at the mm/dd constraint it pays no attention to the YYYY constraint. In the to_char condition if I try using single tick marks it errors out. The only way I can get the tick marks to be accepted in the code is to use 2 single tick marks ''. Any ideas on what I am doing wrong.
    Thanks!

    user520671,
    You are doing the conversion in reverse. Because you're applying a function (TO_CHAR) to the columns in your predicate, you'll be negating the use of any indexes. Not prudent from a performance standpoint.
    Instead, convert your input values to a date and do the comparison that way.
    q := q || ' WHERE ' ||
    '(:P41_W_BEGIN_DT IS NULL OR
        (:P41_W_BEGIN_DT IS NOT NULL AND to_date(:P41_W_BEGIN_DT,''MM/DD/YYYY'') <= HARDWARE_INFO.WARRANTY_END_DT))
    AND
    (:P41_W_END_DT IS NULL OR
        (:P41_W_END_DT IS NOT NULL AND to_date(:P41_W_END_DT,''MM/DD/YYYY'') >= HARDWARE_INFO.WARRANTY_END_DT))'Also ensure that you are truly passing in a 4-digit year.
    Joel

Maybe you are looking for