with temp AS (
SELECT CAST(SUM(sreg.ScrapQuantity) AS INT) AS Quantity,
sreas.Name AS ScrapReason,
to_date((DATEADD(MINUTE, 30 * (DATE_PART(MINUTE, sreg.ScrapTime) / 30), DATEADD(HOUR, TIMESTAMPDIFF(HOUR, '0', sreg.ScrapTime), '0')))) AS DATETIME,
sreg.EquipmentID AS EquipmentID
FROM ScrapRegistration sreg
INNER JOIN ScrapReason sreas ON sreas.ID = sreg.ScrapReasonID
INNER JOIN WorkRequest wr ON wr.ID = sreg.WorkRequestID
INNER JOIN SegmentRequirementEquipmentRequirement srer ON srer.SegmentRequirementID = wr.SegmentRequirementID
GROUP BY DATEADD(MINUTE, 30 * (DATE_PART(MINUTE, sreg.ScrapTime) / 30), DATEADD(HOUR, TIMESTAMPDIFF(HOUR, '0', sreg.ScrapTime), '0')),
sreg.EquipmentID,
sreas.Name
)
select temp.EquipmentID
from RAW_CPMS_AAR.equipment e, temp
Where e.ID = (select * from table(cfn_GetShiftIDFromDateTime_test(temp.DateTime::DATETIME, 0))) --this works with datetime
when i run this query above, i get Processing aborted due to error 300010:391167117; incident 3245754.. I believe this is an issue with the temp.datetime -- when i run the same codebut hardcoding the function input, i get the desired output.
with temp AS (
SELECT CAST(SUM(sreg.ScrapQuantity) AS INT) AS Quantity,
sreas.Name AS ScrapReason,
to_date((DATEADD(MINUTE, 30 * (DATE_PART(MINUTE, sreg.ScrapTime) / 30), DATEADD(HOUR, TIMESTAMPDIFF(HOUR, '0', sreg.ScrapTime), '0')))) AS DATETIME,
sreg.EquipmentID AS EquipmentID
FROM ScrapRegistration sreg
INNER JOIN ScrapReason sreas ON sreas.ID = sreg.ScrapReasonID
INNER JOIN WorkRequest wr ON wr.ID = sreg.WorkRequestID
INNER JOIN SegmentRequirementEquipmentRequirement srer ON srer.SegmentRequirementID = wr.SegmentRequirementID
GROUP BY DATEADD(MINUTE, 30 * (DATE_PART(MINUTE, sreg.ScrapTime) / 30), DATEADD(HOUR, TIMESTAMPDIFF(HOUR, '0', sreg.ScrapTime), '0')),
sreg.EquipmentID,
sreas.Name
)
select temp.EquipmentID
from RAW_CPMS_AAR.equipment e, temp
Where e.ID = (select * from table(cfn_GetShiftIDFromDateTime_test('2021-12-02 10:03:0.00'::datetime, 0))) --this works with datetime
it seems that that somwehere along the line, it's not liking the date format i put in. it's not returning me an error of not liking the input.
here is the function.
CREATE OR REPLACE FUNCTION DB_BI_DEV.RAW_CPMS_AAR.cfn_GetShiftIDFromDateTime (dateTime TIMESTAMP_NTZ(9), shiftCalendarID int)
RETURNS table (shiftID int)
AS
$$
WITH T0 (ShiftCalendarID, CurDay, PrvDay)
AS (
SELECT TOP 1
ID AS ShiftCalendarID,
DATEDIFF( day, BeginDate, dateTime ) % PeriodInDays + 1 AS CurDay,
( CurDay + PeriodInDays - 2 ) % PeriodInDays + 1 AS PrvDay
FROM RAW_CPMS_AAR.ShiftCalendar
WHERE ID = shiftCalendarID
OR ( shiftCalendarID IS NULL
AND Name = 'Factory'
AND BeginDate <= dateTime )
ORDER BY BeginDate DESC
),
T1 (TimeValue)
AS (
SELECT TIME_FROM_PARTS(
EXTRACT(HOUR FROM dateTime),
EXTRACT(MINUTE FROM dateTime),
EXTRACT(SECOND FROM dateTime))
)
SELECT ID as shiftID
FROM RAW_CPMS_AAR.Shift, T0, T1
WHERE Shift.ShiftCalendarID = T0.ShiftCalendarID
AND ( ( FromDay = T0.CurDay AND FromTimeOfDay <= T1.TimeValue AND TillTimeOfDay > T1.TimeValue )
OR ( FromDay = T0.CurDay AND FromTimeOfDay >= TillTimeOfDay AND FromTimeOfDay <= T1.TimeValue )
OR ( FromDay = T0.PrvDay AND FromTimeOfDay >= TillTimeOfDay AND TillTimeOfDay > T1.TimeValue )
)
$$
;
Can anyone help me to understand this big sql query. How do I break it down in small chunks to understand it ?
select t.Instrument as Instrument ,ClearingId as ClearingId,
ISNULL( PrevQty ,0) AS PrevQty,SettlePrice,
ISNULL(TodayBuyQty,0) as TodayBuyQty,
ISNULL( TodaySellQty ,0) AS TodaySellQty,
ISNULL(PrevQty +TodayBuyQty-TodaySellQty,0) as NetQty,
TodayBuyPrice, TodaySellPrice,LTP,PnL,Token
from
(
select Instrument,w.ClearingId as ClearingId,
ISNULL( PrevQty ,0) AS PrevQty,ISNULL(TodayBuyQty,0) as TodayBuyQty,
ISNULL( TodaySellQty ,0) AS TodaySellQty,
TodayAvgBuyPrice as TodayBuyPrice,TodayAvgSellPrice as TodaySellPrice,
LTP,PnL,w.Token
from
(
select Symbol as Instrument, ClearingId,
ISNULL(TodayBuyQty,0) as TodayBuyQty,
TodayAvgBuyPrice,
ISNULL( -TodaySellQty ,0) AS TodaySellQty,
TodayAvgSellPrice, NULL as LTP ,NULL as PnL ,
w.Token as Token
from
(
select Token, sum(Qty) as NetPositionQty, ClearingId,
sum(CASE WHEN Qty < 0 THEN Qty ELSE 0 END) as TodaySellQty,
sum(CASE WHEN Qty > 0 THEN Qty ELSE 0 END) as TodayBuyQty,
sum(CASE WHEN Qty < 0 THEN Qty * Price ELSE 0 END)
/
NULLIF(sum(CASE WHEN Qty < 0 THEN Qty ELSE 0 END), 0) as TodayAvgSellPrice,
sum(CASE WHEN Qty > 0 THEN Qty * Price ELSE 0 END)
/
NULLIF(sum(CASE WHEN Qty > 0 THEN Qty ELSE 0 END), 0) as TodayAvgBuyPrice
from
(
select m.Token,
(CASE WHEN ClearingId = 'SATP' THEN 'STRAITS' ELSE CASE WHEN ClearingId = 'BATP' THEN 'BPI' ELSE 'UOB' END END ) as ClearingId ,
Price/CAST(Multiplier AS float ) as Price,Qty
from
(
select Token , Exchange as ClearingId ,
LastTradePrice as Price ,
CASE WHEN Side = 'S' THEN -LastTradeQuantity ELSE LastTradeQuantity END as Qty
from Strategy_Orders
where ExchangeStatus in (9,10) )m
JOIN TokenMap t ON ( m.Token = t.Token)
UNION ALL
select m.Token, (CASE WHEN ClearingId = 'SATP' THEN 'STRAITS' ELSE CASE WHEN ClearingId = 'BATP' THEN 'BPI' ELSE 'UOB' END END ) as ClearingId ,
Price/CAST(Multiplier AS float ) as Price,
Qty
from
(
select Token , Exchange as ClearingId ,
LastTradePrice as Price ,
CASE WHEN Side = 'S' THEN -LastTradeQuantity ELSE LastTradeQuantity END as Qty
from Manual_Orders
where ExchangeStatus in (9,10) )m
JOIN TokenMap t ON ( m.Token = t.Token)
UNION ALL
select Token , ClearingId , TodayBuyPrice ,
TodayBuyQty as Qty
from EOD_Holdings
where CurrentDate =
( select top 1 CurrentDAte from EOD_Holdings
order by CurrentDAte desc
)
UNION ALL
select Token , ClearingId , TodaySellPrice ,
TodaySellQty as Qty
from EOD_Holdings
where CurrentDate = (
select top 1 CurrentDAte from EOD_Holdings
order by CurrentDAte desc
)
) x
group by Token,ClearingId) w
JOIN(select Token, Symbol from TokenMAp ) h on w.Token = h.Token
) w
FULL OUTER JOIN(
select Token, PrevQty , ClearingId
from EOD_Holdings
where CurrentDate = ( select top 1 CurrentDAte from EOD_Holdings order by CurrentDAte desc
)
) h
on w.Token = h.Token and w.ClearingId = h.ClearingId
)t
JOIN (
select * from LatestSettlePrices
) sp
on t.Instrument = sp.Instrument
You can break the query into chunks by looking at each subquery ("select ..." ) separately and running them to see the results. You need to start with the innermost queries that do not have other select statements in the "from" or "where" clause.
Also note that this query does not seem to be a clear, neither an optimal solution.
You would want to avoid using full outer joins and union all statements for the best performance.
I tried finding the answer, but maybe I am too new to MSSQL, I come from MySQL, so this is my question super simplified to go straight to the point:
Imagine we have a table "Things"
Thingie | Value
--------+-------
Thing1 | 10
Thing1 | 15
Thing1 | 16
In MySQL I could do something like this in a query:
SET #halfvalue := 0;
SELECT Thingie, Value,
(#halfvalue := Value / 2) AS HalfValue,
(#halfvalue / 2) AS HalfOfHalf
FROM Things
Which would return
Thingie | Value | HalfValue | HalfofHalf
--------+-------+-----------+------------
Thing1 | 10 | 5.00 | 2.50
Thing1 | 15 | 7.50 | 3.75
Thing1 | 16 | 8.00 | 4.00
Looks pretty simple, the actual one is a tad more complicated.
My problem is, in MSSQL I can't assign, and use a variable on the same SELECT. And I can't find anything similar to this functionality on this simple level.
Any solutions?
Edit, this is the select that contains all those nasty operations:
SELECT
fvh.DocEntry,
MAX( fvs.SeriesName ) AS "Serie",
MAX( fvh.DocNum - 1000000 ) AS "Número",
MAX( fvh.DocDate ) AS "Fecha",
MAX( fvh.U_FacNit ) AS "NIT",
MAX( fvh.U_FacNom ) AS "Nombre",
MAX( IIF( ISNULL( fvh.Address, '' ) = '', fvh.Address2, fvh.Address ) ) AS "Dirección",
SUM( fvd.GTotal - ISNULL( ncd.GTotal, 0 ) ) AS "Total",
IIF( MAX( fvh.CANCELED ) = 'Y' OR ( SUM( fvd.GTotal - ISNULL( ncd.GTotal, 0 ) ) = 0 ),
'Anulada',
IIF( SUM( fvd.GTotal ) > SUM( ISNULL( ncd.GTotal, 0 ) ) AND ( SUM( ISNULL( ncd.GTotal, 0 ) ) > 0 ),
'Devuelta',
'Emitida' )
) AS "Estado",
ROUND( ( ( SUM( fvd.GTotal - ISNULL( ncd.GTotal, 0 ) ) / 1.12 ) * 0.12 ), 4 ) AS "IVA",
ROUND( SUM( IIF( fvd.U_TipoA = 'BB',
( fvd.GTotal - ISNULL( ncd.GTotal, 0 ) ) - ( ( ( fvd.GTotal - ISNULL( ncd.GTotal, 0 ) ) / 1.12 ) * 0.12 ),
0 ) ), 4) AS "Bien",
ROUND( SUM( IIF( fvd.U_TipoA = 'S',
( fvd.GTotal - ISNULL( ncd.GTotal, 0 ) ) - ( ( ( fvd.GTotal - ISNULL( ncd.GTotal, 0 ) ) / 1.12 ) * 0.12 ),
0 ) ), 4) AS "Servicio",
ROUND( SUM( IIF( fvd.U_TipoA = 'N',
( fvd.GTotal - ISNULL( ncd.GTotal, 0 ) ) - ( ( ( fvd.GTotal - ISNULL( ncd.GTotal, 0 ) ) / 1.12 ) * 0.12 ),
0 ) ), 4) AS "No Aplica",
COUNT(fvd.LineNum) AS "Lineas", SUM(fvd.GTotal) AS "FCTotal",
SUM(ISNULL( ncd.GTotal, 0 )) AS "NCTotal"
/* Facturas */
FROM OINV AS fvh
LEFT JOIN NNM1 AS fvs ON fvs.Series = fvh.Series
LEFT JOIN INV1 as fvd ON fvd.DocEntry = fvh.DocEntry
/* Notas de Credito */
LEFT JOIN RIN1 AS ncd ON ncd.BaseEntry = fvh.DocEntry AND ncd.LineNum = fvd.LineNum
WHERE fvh.DocDate BETWEEN ? AND ? /*AND fvh.DocEntry = 1108*/
GROUP BY fvh.DocEntry
Thank you all for your time. I will dismantle my query and re-do it taking into consideration all of your input. Gracias, totales.
You think you can do this in MySQL:
SET #halfvalue := 0;
SELECT Thingie, Value,
(#halfvalue := Value / 2) AS HalfValue,
(#halfvalue / 2) AS HalfOfHalf
FROM Things;
But you are wrong. Why? MySQL -- as with every other database -- does not guarantee the order of evaluation of expression in a SELECT. The documentation even warns about this:
In the following statement, you might think that MySQL will evaluate #a first and then do an assignment second:
SELECT #a, #a:=#a+1, ...;
However, the order of evaluation for expressions involving user variables is undefined.
In both databases, you can use a subquery. In the most recent versions of MySQL (and just about any other database), you can also use a CTE:
SELECT Thingie, Value, HalfValue,
(HalfValue / 2) AS HalfOfHalf
FROM (SELECT t.*, (Value / 2) AS HalfValue
FROM Things t
) t;
The answer is simple: you can't do that in MSSQL, because when you try it you'll get:
Msg 141, Level 15, State 1, Line 3
A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations.
which you most probably experienced.
The most simple workaround would be:
SELECT Thingie, Value, Value/2, Value/4 from Things
Other method:
select Thingie, Value, HalfValue, HalfValue / 2 from (
SELECT Thingie, Value, Value / 2 HalfValue from Things
) a
No, that doesn't work in SQL. The parameter value is not set until the query completes. You can do it in two steps:
DECLARE #halfvalue FLOAT = 0;
SELECT #halfvalue = ([Value] / 2)
FROM Things ;
SELECT Thingie
, [Value]
, HalfValue = [Value]/2
, HalfAgainValue = #halfvalue / 2
FROM Things ;
I currently have a somewhat large SQL statement that UNIONs the same SELECT statement 3 times each time with a larger date range. IE Last 30 days, Last 90 Days and Last 180 Days. The SQL works just fine and I am even OK with the fact that the query takes quite a while to run, I am just wondering if there is anyway to do the same thing with just one SELECT statement.
Seeing as a couple of people asked to see my code:-
SELECT mdt_userid AS logging_officer,
'Last 30 Days' AS timespan,
ACD_Time,
TRUNCATE (( 1 - ( (TotalAssisting+TotalBRB+TotalShift+TotalLunch+TotalBreak-IF(TotalLunch<(DaysLoggedIn*Lunch),TotalLunch,(DaysLoggedIn*Lunch))-IF((TotalBRB+TotalBreak)<(DaysLoggedIn*1800),(TotalBRB+TotalBreak),(DaysLoggedIn*1800))) / (TotalLoginTime-TotalEreq-TotalDefault) ) ) *100,2) AS Utilization_percent,
TRUNCATE((GRS_total/calls)*100,1) AS Ratio,
IF (TotalACW =0,0,TotalACW / calls) AS ACW,
grs.percent AS percent,
TRUNCATE (((grs_total - wo_ci) / grs_total) *100,2) AS percent_w_ci,
TRUNCATE (calls / ( ((TotalLoginTime-TotalEreq-TotalDefault) /3600) / 8.75 ) ,2) AS call_per_hour,
TRUNCATE (GRS_total / ( ((TotalLoginTime-TotalEreq-TotalDefault) /3600) / 8.75 ) ,2) AS grs_per_hour
FROM (SELECT DISTINCT fullname,
SUM( IF (ReasonCode = '138', `ReasonCodeDuration` , 0) ) AS TotalAssisting,
SUM( IF (ReasonCode = '146', `ReasonCodeDuration` , 0) ) AS TotalBRB,
SUM( IF (ReasonCode = '143', `ReasonCodeDuration` , 0) ) AS TotalShift,
SUM( IF (ReasonCode = '141', `ReasonCodeDuration` , 0) ) AS TotalACW,
SUM( IF (ReasonCode = '231', `ReasonCodeDuration` , 0) ) AS TotalEreq,
SUM( IF (ReasonCode = '0', `ReasonCodeDuration` , 0) ) AS TotalDefault,
COUNT(ReasonCode = '136') AS CountLunch,
SUM( IF (ReasonCode = '136', `ReasonCodeDuration` , 0) ) AS TotalLunch,
SUM( IF (ReasonCode = '137', `ReasonCodeDuration` , 0) ) AS TotalBreak,
SUM( `ReasonCodeDuration` ) AS NRduration
FROM `CiscoAgentNotready`
WHERE StartDate >= '".adjustdate($DateTo,0,0,-30)." 00:00:00'
AND StartDate <= '".$DateTo." 23:59:59'
GROUP BY fullname)
AS notready,
(SELECT DISTINCT agentname,
SUM( loginduration ) AS TotalLoginTime, COUNT(Date(logondate)) as DaysLoggedIn
FROM CiscoAgentLogintime
WHERE logondate >= '".adjustdate($DateTo,0,0,-30)." 00:00:00'
AND logondate <= '".$DateTo." 23:59:59'
GROUP BY agentname)
AS logintime,
(SELECT DISTINCT full_name,
SUM( handled ) AS calls
FROM `CiscoAgentCalls`
WHERE DateCol >= '".adjustdate($DateTo,0,0,-30)."'
AND DateCol <= '".$DateTo."'
GROUP BY full_name)
AS calls,
(SELECT DISTINCT logging_officer,
SUM( first_call ) AS firstcall,
SUM(IF (Config_item = 'unknown', 1, 0) ) AS wo_ci,
COUNT( * ) AS GRS_total,
TRUNCATE ((SUM( first_call ) / COUNT( * )) *100,2) AS percent
FROM (SELECT logging_officer,
IF (logging_officer = `Resolving_Officer` , 1, 0) AS first_call,
Config_item
FROM `callcentergrsdata`
WHERE log_Date >= '".adjustdate($DateTo,0,0,-30)." 00:00:00'
AND log_Date <= '".$DateTo." 23:59:59')
AS a
GROUP BY logging_officer)
AS grs,
(SELECT DISTINCT agtName,
SUM(TalkTime) as sumTalk,
SUM(CallsHandled) as answered,
SUM(TalkTime)/SUM(CallsHandled) as ACD_Time
FROM (SELECT CONCAT( LastName, ', ', FirstName ) AS agtName,
TalkTime,
CallsHandled
FROM `CiscoAgentAHT`
WHERE DateCol >= '".adjustdate($DateTo,0,0,-30)."'
AND DateCol <= '".$DateTo."') as subAHT
GROUP BY agtName)
AS AHT,
techjtblnew
WHERE mdt_userid = '".$user."'
AND notready.fullname = logintime.agentname
AND calls.full_name = notready.fullname
AND calls.full_name = AHT.agtName
AND techjtblnew.cisco = notready.fullname
AND grs.logging_officer = techjtblnew.grs
UNION
SELECT mdt_userid AS logging_officer,
'Last 90 Days' AS timespan,
ACD_Time,
TRUNCATE (( 1 - ( (TotalAssisting+TotalBRB+TotalShift+TotalLunch+TotalBreak-IF(TotalLunch<(DaysLoggedIn*Lunch),TotalLunch,(DaysLoggedIn*Lunch))-IF((TotalBRB+TotalBreak)<(DaysLoggedIn*1800),(TotalBRB+TotalBreak),(DaysLoggedIn*1800))) / (TotalLoginTime-TotalEreq-TotalDefault) ) ) *100,2) AS Utilization_percent,
TRUNCATE((GRS_total/calls)*100,1) AS Ratio,
IF (TotalACW =0,0,TotalACW / calls) AS ACW,
grs.percent AS percent,
TRUNCATE (((grs_total - wo_ci) / grs_total) *100,2) AS percent_w_ci,
TRUNCATE (calls / ( ((TotalLoginTime-TotalEreq-TotalDefault) /3600) / 8.75 ) ,2) AS call_per_hour,
TRUNCATE (GRS_total / ( ((TotalLoginTime-TotalEreq-TotalDefault) /3600) / 8.75 ) ,2) AS grs_per_hour
FROM (SELECT DISTINCT fullname,
SUM( IF (ReasonCode = '138', `ReasonCodeDuration` , 0) ) AS TotalAssisting,
SUM( IF (ReasonCode = '146', `ReasonCodeDuration` , 0) ) AS TotalBRB,
SUM( IF (ReasonCode = '143', `ReasonCodeDuration` , 0) ) AS TotalShift,
SUM( IF (ReasonCode = '141', `ReasonCodeDuration` , 0) ) AS TotalACW,
SUM( IF (ReasonCode = '231', `ReasonCodeDuration` , 0) ) AS TotalEreq,
SUM( IF (ReasonCode = '0', `ReasonCodeDuration` , 0) ) AS TotalDefault,
COUNT(ReasonCode = '136') AS CountLunch,
SUM( IF (ReasonCode = '136', `ReasonCodeDuration` , 0) ) AS TotalLunch,
SUM( IF (ReasonCode = '137', `ReasonCodeDuration` , 0) ) AS TotalBreak,
SUM( `ReasonCodeDuration` ) AS NRduration
FROM `CiscoAgentNotready`
WHERE StartDate >= '".adjustdate($DateTo,0,0,-90)." 00:00:00'
AND StartDate <= '".$DateTo." 23:59:59'
GROUP BY fullname)
AS notready,
(SELECT DISTINCT agentname,
SUM( loginduration ) AS TotalLoginTime, COUNT(Date(logondate)) as DaysLoggedIn
FROM CiscoAgentLogintime
WHERE logondate >= '".adjustdate($DateTo,0,0,-90)." 00:00:00'
AND logondate <= '".$DateTo." 23:59:59'
GROUP BY agentname)
AS logintime,
(SELECT DISTINCT full_name,
SUM( handled ) AS calls
FROM `CiscoAgentCalls`
WHERE DateCol >= '".adjustdate($DateTo,0,0,-90)."'
AND DateCol <= '".$DateTo."'
GROUP BY full_name)
AS calls,
(SELECT DISTINCT logging_officer,
SUM( first_call ) AS firstcall,
SUM(IF (Config_item = 'unknown', 1, 0) ) AS wo_ci,
COUNT( * ) AS GRS_total,
TRUNCATE ((SUM( first_call ) / COUNT( * )) *100,2) AS percent
FROM (SELECT logging_officer,
IF (logging_officer = `Resolving_Officer` , 1, 0) AS first_call,
Config_item
FROM `callcentergrsdata`
WHERE log_Date >= '".adjustdate($DateTo,0,0,-90)." 00:00:00'
AND log_Date <= '".$DateTo." 23:59:59')
AS a
GROUP BY logging_officer)
AS grs,
(SELECT DISTINCT agtName,
SUM(TalkTime) as sumTalk,
SUM(CallsHandled) as answered,
SUM(TalkTime)/SUM(CallsHandled) as ACD_Time
FROM (SELECT CONCAT( LastName, ', ', FirstName ) AS agtName,
TalkTime,
CallsHandled
FROM `CiscoAgentAHT`
WHERE DateCol >= '".adjustdate($DateTo,0,0,-90)."'
AND DateCol <= '".$DateTo."') as subAHT
GROUP BY agtName)
AS AHT,
techjtblnew
WHERE mdt_userid = '".$user."'
AND notready.fullname = logintime.agentname
AND calls.full_name = notready.fullname
AND calls.full_name = AHT.agtName
AND techjtblnew.cisco = notready.fullname
AND grs.logging_officer = techjtblnew.grs
UNION
SELECT mdt_userid AS logging_officer,
'Last 120 Days' AS timespan,
ACD_Time,
TRUNCATE (( 1 - ( (TotalAssisting+TotalBRB+TotalShift+TotalLunch+TotalBreak-IF(TotalLunch<(DaysLoggedIn*Lunch),TotalLunch,(DaysLoggedIn*Lunch))-IF((TotalBRB+TotalBreak)<(DaysLoggedIn*1800),(TotalBRB+TotalBreak),(DaysLoggedIn*1800))) / (TotalLoginTime-TotalEreq-TotalDefault) ) ) *100,2) AS Utilization_percent,
TRUNCATE((GRS_total/calls)*100,1) AS Ratio,
IF (TotalACW =0,0,TotalACW / calls) AS ACW,
grs.percent AS percent,
TRUNCATE (((grs_total - wo_ci) / grs_total) *100,2) AS percent_w_ci,
TRUNCATE (calls / ( ((TotalLoginTime-TotalEreq-TotalDefault) /3600) / 8.75 ) ,2) AS call_per_hour,
TRUNCATE (GRS_total / ( ((TotalLoginTime-TotalEreq-TotalDefault) /3600) / 8.75 ) ,2) AS grs_per_hour
FROM (SELECT DISTINCT fullname,
SUM( IF (ReasonCode = '138', `ReasonCodeDuration` , 0) ) AS TotalAssisting,
SUM( IF (ReasonCode = '146', `ReasonCodeDuration` , 0) ) AS TotalBRB,
SUM( IF (ReasonCode = '143', `ReasonCodeDuration` , 0) ) AS TotalShift,
SUM( IF (ReasonCode = '141', `ReasonCodeDuration` , 0) ) AS TotalACW,
SUM( IF (ReasonCode = '231', `ReasonCodeDuration` , 0) ) AS TotalEreq,
SUM( IF (ReasonCode = '0', `ReasonCodeDuration` , 0) ) AS TotalDefault,
COUNT(ReasonCode = '136') AS CountLunch,
SUM( IF (ReasonCode = '136', `ReasonCodeDuration` , 0) ) AS TotalLunch,
SUM( IF (ReasonCode = '137', `ReasonCodeDuration` , 0) ) AS TotalBreak,
SUM( `ReasonCodeDuration` ) AS NRduration
FROM `CiscoAgentNotready`
WHERE StartDate >= '".adjustdate($DateTo,0,0,-120)." 00:00:00'
AND StartDate <= '".$DateTo." 23:59:59'
GROUP BY fullname)
AS notready,
(SELECT DISTINCT agentname,
SUM( loginduration ) AS TotalLoginTime, COUNT(Date(logondate)) as DaysLoggedIn
FROM CiscoAgentLogintime
WHERE logondate >= '".adjustdate($DateTo,0,0,-120)." 00:00:00'
AND logondate <= '".$DateTo." 23:59:59'
GROUP BY agentname)
AS logintime,
(SELECT DISTINCT full_name,
SUM( handled ) AS calls
FROM `CiscoAgentCalls`
WHERE DateCol >= '".adjustdate($DateTo,0,0,-120)."'
AND DateCol <= '".$DateTo."'
GROUP BY full_name)
AS calls,
(SELECT DISTINCT logging_officer,
SUM( first_call ) AS firstcall,
SUM(IF (Config_item = 'unknown', 1, 0) ) AS wo_ci,
COUNT( * ) AS GRS_total,
TRUNCATE ((SUM( first_call ) / COUNT( * )) *100,2) AS percent
FROM (SELECT logging_officer,
IF (logging_officer = `Resolving_Officer` , 1, 0) AS first_call,
Config_item
FROM `callcentergrsdata`
WHERE log_Date >= '".adjustdate($DateTo,0,0,-120)." 00:00:00'
AND log_Date <= '".$DateTo." 23:59:59')
AS a
GROUP BY logging_officer)
AS grs,
(SELECT DISTINCT agtName,
SUM(TalkTime) as sumTalk,
SUM(CallsHandled) as answered,
SUM(TalkTime)/SUM(CallsHandled) as ACD_Time
FROM (SELECT CONCAT( LastName, ', ', FirstName ) AS agtName,
TalkTime,
CallsHandled
FROM `CiscoAgentAHT`
WHERE DateCol >= '".adjustdate($DateTo,0,0,-120)."'
AND DateCol <= '".$DateTo."') as subAHT
GROUP BY agtName)
AS AHT,
techjtblnew
WHERE mdt_userid = '".$user."'
AND notready.fullname = logintime.agentname
AND calls.full_name = notready.fullname
AND calls.full_name = AHT.agtName
AND techjtblnew.cisco = notready.fullname
AND grs.logging_officer = techjtblnew.grs
Seems like you could get away with a complex grouping. E.g., here's a generic way to do it with records:
SELECT
count(*),
MIN(creation)
FROM record
WHERE creation > CURDATE() - INTERVAL 120 DAY
GROUP BY
IF(creation>CURDATE() - INTERVAL 30 DAY,'030',
IF(creation>CURDATE() - INTERVAL 90 DAY,'090',
IF(creation>CURDATE() - INTERVAL 120 DAY,'120',
'OLDER'
)
)
)
You would want to add the records as you go, as each range is exclusive.
Here's a sample output:
+----------+---------------+
| count(*) | MIN(creation) |
+----------+---------------+
| 1472 | 2012-01-08 |
| 2336 | 2011-11-09 |
| 1528 | 2011-10-10 |
| 5336 | 2011-10-10 |
+----------+---------------+
4 rows in set (0.13 sec)
Yes. Just query for the last 180 days and parse it in the software layer.
If you want an indicator of which one each row is, you can use CASE or IF statements:
http://dev.mysql.com/doc/refman/5.0/en/if-statement.html
IF search_condition THEN statement_list
[ELSEIF search_condition THEN statement_list] ...
[ELSE statement_list]
END IF
http://dev.mysql.com/doc/refman/5.0/en/case-statement.html
CASE case_value
WHEN when_value THEN statement_list
[WHEN when_value THEN statement_list] ...
[ELSE statement_list]
END CASE
UPDATE
Ok, now that I know what you are going for I can provide a better solution that I believe will fit your needs.
I don't think that there is a way out of doing UNION BUT you if you do the UNION ahead of time adding a column for the various time spans you can just query once on the results.
In this example, I create a column called span during the UNION. The t1 is the resulting "table". Since span is different for each date range, the rows will show up multiple times.
Example Table:
mysql> select * from test;
+----+------------+
| id | when |
+----+------------+
| 1 | 2012-02-01 |
| 2 | 2012-01-01 |
| 3 | 2011-09-01 |
+----+------------+
Query With Unions:
mysql>
-> SELECT *, 1 as 'span' FROM `test` WHERE `when` > '2012-01-15'
-> UNION
-> SELECT *, 2 as 'span' FROM `test` WHERE `when` > '2011-12-15'
-> UNION
-> SELECT *, 3 as 'span' FROM `test` WHERE `when` > '2011-08-15';
+----+------------+------+
| id | when | span |
+----+------------+------+
| 1 | 2012-02-01 | 1 |
| 2 | 2012-01-01 | 2 |
| 1 | 2012-02-01 | 2 |
| 3 | 2011-09-01 | 3 |
| 2 | 2012-01-01 | 3 |
| 1 | 2012-02-01 | 3 |
+----+------------+------+
Query Using That Union (custom SELECT and WHERE t1.id > 0):
mysql>
-> SELECT
-> `id`,
-> `when`,
-> if(`span` = 1, 'Last 30 Days',
-> if(`span` = 2, 'Last 60 Days',
-> 'Last 180 Days')) as 'Timespan'
-> FROM (
-> SELECT *, 1 as 'span' FROM `test` WHERE `when` > '2012-01-15'
-> UNION
-> SELECT *, 2 as 'span' FROM `test` WHERE `when` > '2011-12-15'
-> UNION
-> SELECT *, 3 as 'span' FROM `test` WHERE `when` > '2011-08-15'
-> ) as t1
-> WHERE t1.id > 0;
+----+------------+---------------+
| id | when | Timespan |
+----+------------+---------------+
| 1 | 2012-02-01 | Last 30 Days |
| 2 | 2012-01-01 | Last 60 Days |
| 1 | 2012-02-01 | Last 60 Days |
| 3 | 2011-09-01 | Last 180 Days |
| 2 | 2012-01-01 | Last 180 Days |
| 1 | 2012-02-01 | Last 180 Days |
+----+------------+---------------+
You will do all of your query stuff off of t1, not off the table itself. Adding the extra column in the creation of t1 allows each row to appear multiple times as the extra row will cause it to be unique.