Related
I'm trying to figure out how to flip this from a table format to a column format.
Hi, I know how to create a SQL HTML Email via table format: i.e
Customer Address City
Joe 123 Here Oakland
but i need to be able to flip this to look like
Customer: Joe
Address: 123 Here
City: Oakland
I'm using SQL 2012
Any help would be appreciated
Please advise
DECLARE #xmlinv NVARCHAR(MAX);
DECLARE #bodyinv NVARCHAR(MAX);
DECLARE #trrowinv NVARCHAR(MAX);
DECLARE #tempemaillistinv NVARCHAR(MAX);
DECLARE #subject_anomaly NVARCHAR(MAX);
SET #subject_anomaly
= N'Inventory Adjustments ' + CAST(#COUNTSinv AS VARCHAR(3)) + N' '
+ LEFT(CONVERT(VARCHAR(10), GETDATE(), 101), 3) + SUBSTRING(CONVERT(VARCHAR(10), GETDATE(), 101), 4, 3)
+ RIGHT(CONVERT(VARCHAR(10), GETDATE(), 101), 2);
SET #xmlinv
= CAST(
(
SELECT T4.product AS 'td',
'',
T4.available AS 'td',
'',
CASE
WHEN T4.quarantine IS NULL THEN
0
ELSE
T4.quarantine
END AS 'td',
'',
CASE
WHEN T4.labels IS NULL THEN
0
ELSE
T4.labels
END AS 'td',
'',
T4.MinLog AS 'td',
'',
T.available AS 'td',
'',
CASE
WHEN T.quarantine IS NULL THEN
0
ELSE
T.quarantine
END AS 'td',
'',
CASE
WHEN T.labels IS NULL THEN
0
ELSE
T.labels
END AS 'td',
'',
T.MinLog AS 'td'
--SELECT T4.product,T4.available,T4.quarantine,T4.labels,T4.MinLog,T.available,T.quarantine,T.labels,T.MinLog
FROM #t4 AS T4
LEFT OUTER JOIN #t3 AS T3
ON T4.MaxRow2 = T3.MaxRow
AND T4.product = T3.product
LEFT OUTER JOIN #t2 AS T2
ON T4.MaxRow2 = T2.MaxRow
AND T4.product = T2.product
LEFT OUTER JOIN #temp AS T
ON T4.MaxRow2 = T.therow + 1
AND T4.product = T.product
ORDER BY 1
--ORDER BY 1,3 desc
FOR XML PATH('tr'), ELEMENTS
)
AS
NVARCHAR(MAX));
SET #bodyinv
= N'<html><H2>Adjustments</H2><body bgcolor=white><table border=1 style=''border:1px;background-color:#FFFFCC;bordercolor:#FFCC00'' cellpadding=''1'' cellspacing=''0''>';
SET #trrowinv
= N'<tr><th>Product</th><th>NewAvailable</th><th>NewQuarantine</th><th>NewLabels</th><th>LastUpdate</th><th>OldAvailable</th><th>OldQuarantine</th><th>OldLabels</th><th>PriorUpdate</th></tr>';
SET #bodyinv = #bodyinv + #trrowinv + #xmlinv + N'</table></body></html>';
SET #tempemaillistinv = N'abc#abc.com';
EXEC [msdb].[dbo].[sp_send_dbmail] #recipients = #tempemaillistinv,
#body = #bodyinv,
#body_format = 'HTML',
#subject = #subject_anomaly,
#profile_name = 'abc';
I would like to write two While Syntax.
The results I expect are as follows.
when 'H'
tagName1, tagName2, tagname3
when 'D'
tagName1, tagName2, tagname3
when 'M'
tagName1, tagName2, tagname3
when 'Y'
tagName1, tagName2, tagname3
But it didn't worked....
Below is the code that I wrote, while I play it only once.
Any advice, please..
DECLARE tagList varchar(255) DEFAULT 'tagName1,tagName2,tagName3';
DECLARE tagTypeList varchar(150) DEFAULT 'H,D,M,Y';
WHILE tagTypeList != '' DO
WHILE tagList != '' DO
SET tagNameArray = SUBSTRING_INDEX(tagList, ',', 1);
SET tagTypeArray = SUBSTRING_INDEX(tagTypeList, ',', 1);
IF(tagTypeArray = 'H') THEN
SET aDate = (SELECT (DATE_ADD(nDateTime, INTERVAL -1 HOUR)));
SET ago_Y = (SELECT DATE_FORMAT(aDate,'%Y'));
SET ago_M = (SELECT DATE_FORMAT(aDate,'%m'));
SET ago_D = (SELECT DATE_FORMAT(aDate,'%d'));
SET ago_H = (SELECT DATE_FORMAT(aDate,'%H'));
SET ago_W = (SELECT DATE_FORMAT(aDate,'%w'));
ELSEIF(tagTypeArray = 'D') THEN
SET aDate = (SELECT (DATE_ADD(nDateTime, INTERVAL -1 DAY)));
SET ago_Y = (SELECT DATE_FORMAT(aDate,'%Y'));
SET ago_M = (SELECT DATE_FORMAT(aDate,'%m'));
SET ago_D = (SELECT DATE_FORMAT(aDate,'%d'));
SET ago_H = 0;
SET ago_W = 0;
ELSEIF(tagTypeArray = 'M') THEN
SET aDate = (SELECT (DATE_ADD(nDateTime, INTERVAL -1 MONTH)));
SET ago_Y = (SELECT DATE_FORMAT(aDate,'%Y'));
SET ago_M = (SELECT DATE_FORMAT(aDate,'%m'));
SET ago_D = 0;
SET ago_H = 0;
SET ago_W = 0;
ELSEIF(tagTypeArray = 'Y') THEN
SET aDate = (SELECT (DATE_ADD(nDateTime, INTERVAL -1 YEAR)));
SET ago_Y = (SELECT DATE_FORMAT(aDate,'%Y'));
SET ago_M = 0;
SET ago_D = 0;
SET ago_H = 0;
SET ago_W = 0;
END IF;
SET selectValue = (SELECT tagvalue FROM datasource WHERE tagname = tagNameArray and tagtype = tagTypeArray and y=ago_Y and m=ago_M and d=ago_D and h=ago_H);
IF(selectValue IS NULL OR selectValue = '')
THEN
SET old_Value_3M = (Select LastValue from BwAnalogTable where TagName = tagNameArray and LogDate >= ago_3M order by LogDate desc, LogTime desc limit 1);
# Here Insert Querty
END IF;
IF LOCATE(',', tagList) > 0 THEN
SET tagList = SUBSTRING(tagList, LOCATE(',', tagList) + 1);
ELSE
SET tagList = '';
END IF;
END WHILE;
IF LOCATE(',', tagTypeList) > 0 THEN
SET tagTypeList = SUBSTRING(tagTypeList, LOCATE(',', tagTypeList) + 1);
ELSE
SET tagTypeList = '';
END IF;
END WHILE;
I have modified the code as shown below.
DECLARE done INT DEFAULT FALSE;
DECLARE tagType2 VARCHAR(255) DEFAULT '';
DECLARE tagName2 VARCHAR(255) DEFAULT '';
DECLARE tagType_Cur CURSOR for select tagType from tbtagtype;
DECLARE tagName_Cur CURSOR for select tagName from tbtaglist;
OPEN tagType_Cur;
LOOP1: LOOP
FETCH tagType_Cur INTO tagType2;
IF done THEN
CLOSE tagType_Cur;
LEAVE LOOP1;
END IF;
########## here insert your core query ###############
OPEN tagName_Cur;
LOOP2: LOOP
FETCH tagName_Cur INTO tagName2;
IF done THEN
CLOSE tagName_Cur;
SET done = FALSE;
LEAVE LOOP2;
END IF;
########## here insert your core query ###############
END LOOP LOOP2;
END LOOP LOOP1;
I am working with Split string method, I have done with splitting a string into fixed length chunks, but the issue is, it breaks the word , I want to keep intact the word and on the base of "SPACE" character ,Split down.
Below I am attaching the Function with test result as well.
Kindly guide or instruct me how to work with.
/*
Select dbo.SplitFixedLengthString('This is me , I am going to split this string in such a way that it will not break any word, rather it keeps word',16)
*/
CREATE FUNCTION [dbo].[SplitFixedLengthString]
(
#string NVARCHAR(MAX) ,
#stringlength INT
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
DECLARE #tempStr NVARCHAR(MAX)
DECLARE #finalString NVARCHAR(MAX)
IF LEN(#string) > 0
AND #stringlength > 0
BEGIN
SELECT #tempStr = ''
DECLARE #i INT
SET #i = 1
WHILE #i <= LEN(#string)
BEGIN
SELECT #tempStr = #tempStr + SUBSTRING(#string, #i,#stringlength) + (CHAR(13) + CHAR(10))
SET #i = #i + #stringlength
END
END
RETURN #tempStr
END
Test Result:
This is me , I a
m going to split
this string in
such a way that
it will not brea
k any word, rath
er it keeps word
(1 row(s) affected)
As we can see the line one of output is splitting the word "am" like wise the line 4,5.
suggest me solution please.
Here are my efforts:
--DECLARE #x VARCHAR(32) = 'xyzxyzyyythgetdghydgsh j';
--SELECT LEN(#x) - CHARINDEX(' ', REVERSE(#x)) + 1;
DECLARE #string NVARCHAR(MAX)
SELECT #string = 'This is me , I am going to split this string in such a way that it will not break any word, rather it keeps word'
--SELECT #string = 'This is me,I am going to Trim off things in such a way that it will add newline having '
DECLARE #stringlength INT
SELECT #stringlength = 11
BEGIN
DECLARE #tempStr NVARCHAR(MAX)
DECLARE #finalString NVARCHAR(MAX) = ''
IF LEN(#string) > 0
AND #stringlength > 0
BEGIN
SELECT #tempStr = ''
DECLARE #start_index INT = 1
DECLARE #last_index INT = 0
DECLARE #lastindex INT = LEN(#string)-1
WHILE #start_index < #lastindex
BEGIN
SELECT #tempStr = SUBSTRING(#string, #start_index,#stringlength )
IF RIGHT(#tempStr,1) = ' '
BEGIN
SET #finalString = #finalString + #tempStr + (CHAR(13) + CHAR(10))
SET #start_index = #start_index + #stringlength
END
ELSE
BEGIN
--SELECT #last_index = LEN(#tempStr) - CHARINDEX(' ', REVERSE(#tempStr)) + 1;
SELECT #last_index = LEN(#tempStr) - CHARINDEX(' ',REVERSE(#tempStr))
IF #last_index = 0
BEGIN
SET #finalString = #finalString + LTRIM(SUBSTRING(#tempStr, 1,LEN(#tempStr)+1))+ (CHAR(13) + CHAR(10))
SET #start_index = #start_index + LEN(#tempStr)
END
ELSE
BEGIN
SET #finalString = #finalString + LTRIM(SUBSTRING(#tempStr, 1,#last_index +1))+ (CHAR(13) + CHAR(10))
SET #start_index = #start_index + #last_index
END
END
IF #start_index + #stringlength >= #lastindex
BEGIN
SET #finalString = #finalString + LTRIM(SUBSTRING(#string, #start_index,(#lastindex - #start_index)+1))+ (CHAR(13) + CHAR(10))
SET #start_index = #start_index + (#lastindex - #start_index)
END
END
END
SELECT #finalString
END
Here is the output
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
This is me
, I am
going to
split
this
string in
such a way
that it
will not
break any
word,
rather it
keeps wor
(1 row(s) affected)
After a little effort I have written this code. and its working fine, although a bit tricky task.
ALTER FUNCTION [dbo].[SplitFixedLengthString]
(
#string NVARCHAR(MAX) ,
#stringlength INT
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
DECLARE #tempStr NVARCHAR(MAX)
DECLARE #finalString NVARCHAR(MAX) = ''
IF LEN(#string) > 0
AND #stringlength > 0
BEGIN
SELECT #tempStr = ''
DECLARE #start_index INT = 1
DECLARE #last_index INT = 0
DECLARE #lastindex INT = LEN(#string)
DECLARE #NextChar VARCHAR(1) = ''
WHILE #start_index < #lastindex
BEGIN
SELECT #tempStr = SUBSTRING(#string, #start_index,#stringlength )
IF RIGHT(#tempStr,1) = ' '
BEGIN
SET #finalString = #finalString + #tempStr + (CHAR(13) + CHAR(10))
SET #start_index = #start_index + #stringlength
END
ELSE
BEGIN
SELECT #last_index = LEN(#tempStr) - CHARINDEX(' ',REVERSE(#tempStr))
SET #NextChar = SUBSTRING(#string, #start_index +LEN(#tempStr),1)
IF #last_index = 0 AND #NextChar = ' '
BEGIN
SET #finalString = #finalString + LTRIM(SUBSTRING(#tempStr, 1,LEN(#tempStr)-1))+(CHAR(13) )
SET #start_index = #start_index + LEN(#tempStr)
END
IF #last_index = 0 AND #NextChar <> ' '
BEGIN
SET #finalString = #finalString + LTRIM(SUBSTRING(#tempStr, 1,LEN(#tempStr)-1))+ '_'+ (CHAR(13) )
SET #start_index = #start_index + LEN(#tempStr) -1
END
ELSE IF (#last_index) = LEN(#tempStr)
BEGIN
SET #finalString = #finalString + LTRIM(SUBSTRING(#tempStr, 1,LEN(#tempStr)-1))+ '_'+ (CHAR(13) )
SET #start_index = #start_index + LEN(#tempStr) -1
END
ELSE IF #last_index <> 0 AND #NextChar = ' '
BEGIN
SET #finalString = #finalString + LTRIM(SUBSTRING(#tempStr, 1,LEN(#tempStr)))+ (CHAR(13) )
SET #start_index = #start_index + LEN(#tempStr)
END
ELSE IF (LEN(#tempStr) - #last_index) = 2 AND #NextChar <> ' '
BEGIN
SET #finalString = #finalString + LTRIM(SUBSTRING(#tempStr, 1,LEN(#tempStr)-1))+ (CHAR(13) )
SET #start_index = #start_index + LEN(#tempStr) -1
END
ELSE IF (#last_index) <> 0 AND #NextChar <> ' '
BEGIN
SET #finalString = #finalString + LTRIM(SUBSTRING(#tempStr, 1,LEN(#tempStr)-1))+ '_'+ (CHAR(13) )
SET #start_index = #start_index + LEN(#tempStr) -1
END
ELSE
BEGIN
SET #finalString = #finalString + LTRIM(SUBSTRING(#tempStr, 1,#last_index ))+ (CHAR(13) )
SET #start_index = #start_index + #last_index
END
END
IF #start_index + #stringlength >= #lastindex
BEGIN
SET #finalString = #finalString + LTRIM(SUBSTRING(#string, #start_index,(#lastindex - #start_index)+1))+ (CHAR(13) )
SET #start_index = #start_index + (#lastindex - #start_index)
END
END
END
RETURN #finalString
END
I have a table like below:
panelistId DTTM
337322 7/27/2014 19:39
337322 7/27/2014 19:29
317420 7/27/2014 10:22
317420 7/27/2014 10:22
317420 7/27/2014 9:27
336333 7/27/2014 5:41
336333 7/27/2014 3:26
336333 7/27/2014 3:26
336333 7/27/2014 1:25
I am looking for a SQL select query to have below fields from this table:
panelistId | #ofExposures | Exposure_DTTM1 | Exposure_DTTM2 | Exposure_DTTM3 | Exposure_DTTM4 | Exposure_DTTM5 | etc
337322 | 2 | 7/27/2014 19:39 | 7/27/2014 19:29 | | |
Here number of DTTM will be different for each id. If an id will have only 3 DTTM then for rest of the DTTM columns it can be blank.
This should do the trick. Hope it helps
DECLARE #Table2 TABLE (RowID INT IDENTITY(1, 1),
panelistId INT ,
#ofExposures VARCHAR(MAX),
Exposure_DTTMVARCHAR(MAX))
DECLARE #Table TABLE (ID INT ,
DTTM VARCHAR(30)) INSERT INTO #Table (ID,
DTTM) VALUES ('337322', '7/27/2014 19:39'), ('337322', '7/27/2014 19:29'), ('317420', '7/27/2014 10:22'), ('317420', '7/27/2014 10:22'), ('317420', '7/27/2014 9:27'), ('336333', '7/27/2014 5:41'), ('336333', '7/27/2014 3:26'), ('336333', '7/27/2014 3:26'), ('336333', '7/27/2014 1:25'); WITH cte_StageOne
AS (
SELECT ROW_NUMBER() OVER(PARTITION BY id ORDER BY CAST(t.DTTM AS DATETIME) ) AS OrderID, *
FROM #Table AS t
)
INSERT INTO #Table2
SELECT MAX(ID) AS panelistId,
MAX(OrderID) AS #ofExposures,
STUFF((
SELECT ' | ' + cso.DTTM
FROM cte_StageOne AS cso
WHERE ocso.ID = cso.ID
FOR XML PATH('')
), 1, 3, '') AS #Exposure
FROM cte_StageOne AS ocso
GROUP BY ID
--SELECT * FROM #Table2
DECLARE #MaxDTTM INT DECLARE #StartLoop INT DECLARE #EndLoop INT DECLARE #ColumnList VARCHAR(MAX)
SELECT #MaxDTTM = MAX(#ofExposures),
#EndLoop = MAX(RowID),
#StartLoop = MIN(RowID) FROM #Table2
SET #ColumnList = 'panelistId|#ofExposures|Exposure_DTTM1'
WHILE #StartLoop <= #EndLoop
BEGIN
SET #ColumnList = #ColumnList + '|Exposure_DTTM' + CAST(#StartLoop + 1 AS VARCHAR(3))
SET #StartLoop = #StartLoop + 1
END SET #ColumnList = #ColumnList
SET #StartLoop = 1
WHILE #StartLoop <= #EndLoop
BEGIN
DECLARE #in_panelistId VARCHAR(10)
DECLARE #in_ofExposures VARCHAR(10)
DECLARE #in_Exposure_DTTM VARCHAR(MAX)
SELECT #in_panelistId = panelistId,
#in_ofExposures = #ofExposures,
#in_Exposure_DTTM = Exposure_DTTM
FROM #Table2
WHERE RowID = #StartLoop
SET #ColumnList = #ColumnList + CHAR(13) + CHAR(10) + #in_panelistId + '|' + #in_ofExposures + '|' + #in_Exposure_DTTM + REPLICATE('|', #MaxDTTM - #in_ofExposures)
--PRINT REPLICATE('|',#MaxDTTM - #in_ofExposures)
SET #StartLoop = #StartLoop + 1
END PRINT #ColumnList
I have run into a scenario that is giving me a null error and do not know how to fix it - can't even figure out where the null error is throwing.
CREATE PROCEDURE reportFreeCooling(
IN fromDate VARCHAR (50),
IN toDate VARCHAR (50),
IN timeZone VARCHAR (50)
)
BEGIN
DECLARE startDate VARCHAR (50);
DECLARE endDate VARCHAR (50);
DECLARE startDateOriginal VARCHAR (50);
DECLARE mylogID INT;
DECLARE myItemId varchar (50);
DECLARE myItemId2 varchar (50);
DECLARE xHours varchar (50);
DECLARE endHoursNull varchar(50);
DECLARE endHoursNotNull varchar (50);
DECLARE firstRow INT;
DECLARE firstRowDate varchar(50);
DECLARE minRowDate varchar (50);
DECLARE minRow int;
SET startDate = FROM_UNIXTIME(fromDate/1000);
SET endDate = FROM_UNIXTIME(toDate/1000);
SET startDateOriginal = FROM_UNIXTIME(fromDate/1000);
SET mylogID = (SELECT logID FROM logs WHERE details LIKE 'FCT%' LIMIT 1);
SET myItemID = (SELECT i.itemId FROM items i WHERE i.name LIKE '%KW PRE%');
SET myItemID2 = (SELECT i.itemId FROM items i WHERE i.name LIKE '%KW STA%');
DROP TABLE IF EXISTS tempTable3 CASCADE;
SET #sql = NULL;
SET #sql = CONCAT(
'CREATE TEMPORARY TABLE tempTable3 AS (SELECT
#row := #row + 1 AS rownum,
a.logId,a.name AS Type,
L1.recordId,
L2.recordId AS next_recordId,
L1.completed,
L2.completed AS next_completed,
L3.completed AS first_completed,
L1.activityId AS activityJoin,
L2.activityId AS next_activityId,
IF(L1.activityId = L2.activityId, 1, NULL) AS isError,
CASE
when a.name LIKE ''%Enable%'' THEN time_to_sec(timediff(L2.completed, L1.completed)) / 3600
ELSE NULL
END AS coolingHours,
TO_SECONDS(L2.completed) - TO_SECONDS(L1.completed) AS timeInSeconds,
((SUBSTR(l.details, INSTR(l.details, '':'') + 1))) AS charge,
time_to_sec(timediff(''', endDate, ''', ''', startDate, ''')) / 3600 AS totalTimeRange,
CONVERT_TZ(''', startDate, ''', ''UTC'', ''', timeZone, ''') AS startingDate,
CONVERT_TZ(''', endDate, ''', ''UTC'', ''', timeZone, ''') AS endingDate,
(L1.item', myItemID, ' - L1.item', myItemID2, ') AS itemDifference,
((L1.item', myItemID, ' - L1.item', myItemID2, ') *
(TIME_TO_SEC(TIMEDIFF(L2.completed, L1.completed))/3600)) AS kwDifference,
((L1.item', myItemID, ' - L1.item', myItemID2, ') * (SUBSTR(l.details, INSTR(l.details, '':'') + 1))) AS cost,
((((L1.item', myItemID, ' - L1.item', myItemID2, ') * (SUBSTR(l.details, INSTR(l.details,'':'') + 1)))
* (TIME_TO_SEC(TIMEDIFF(L2.completed, L1.completed)) / 3600))) AS costT,
DATABASE() AS databaseName, i.itemId ,l.details
FROM
(SELECT #row:=0)R,
(SELECT T1.completed
, (SELECT MIN(T2.completed)
FROM log',mylogID, ' T2
WHERE T2.completed > T1.completed) AS next_completed
, (SELECT MAX(T2.completed)
FROM log',mylogID, ' T2
WHERE T2.completed < T1.completed) AS frst_completed
FROM log',mylogID, ' T1
ORDER BY T1.completed
)TimeOrder
LEFT JOIN log', mylogID, ' L1 ON (L1.completed = TimeOrder.completed)
LEFT JOIN log', mylogID, ' L2 ON (L2.completed = TimeOrder.next_completed)
LEFT JOIN log', mylogID, ' L3 ON (L3.completed = TimeOrder.frst_completed)
LEFT JOIN activities a ON L1.activityId = a.activityId
LEFT JOIN logs l ON a.logId = l.logId
LEFT JOIN items i ON l.logId = i.logId AND i.name LIKE ''%KW PRE%''
)order by L1.completed');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
/* sets next row hours when date is after startdate and first is null */
SET #startDate = (SELECT MIN(completed) FROM tempTable3 WHERE coolingHours is NULL AND
completed BETWEEN startDate AND endDate);
SET #startDate2 = (SELECT MAX(completed) FROM tempTable3 WHERE completed < #startDate);
SET startDate = #startDate2;
/* sets end hours when last row is enabled and next_completed is greater than end date */
SET #endHoursNotNull = (SELECT MAX(completed) AS maxCompletedDateAndCoolingHoursNotNull FROM tempTable3 WHERE coolingHours is NOT NULL AND
completed BETWEEN startDate AND endDate);
SET endHoursNotNull= #endHoursNotNull;
SET #endHoursNull = (SELECT MAX(completed) AS maxCompletedAndCoolingHoursNull FROM tempTable3 WHERE coolingHours is NULL AND
completed BETWEEN startDate AND endDate);
SET endHoursNull = #endHoursNull;
/* sets first row hours when date is after startdate and first enabled */
SET firstRowDate = (SELECT MIN(completed) FROM tempTable3);
IF firstRowDate > startDateOriginal THEN SET startDateOriginal = firstRowDate; END IF;
SET #newcoolingHours = (SELECT (time_to_sec(timediff(next_completed, startDateOriginal)) / 3600) AS newCoolingHours
FROM tempTable3 WHERE completed >= startDateOriginal
AND completed BETWEEN startDate AND endDate LIMIT 1);
SET xHours = #newCoolingHours;
SET minRowDate = (SELECT MIN(completed) FROM tempTable3 WHERE completed BETWEEN startDate AND endDate LIMIT 1 );
SET minRow = (SELECT MIN(rowNum)FROM tempTable3 WHERE completed BETWEEN startDate AND endDate LIMIT 1 );
/* set first row number and hours for when first row in log(itemId) is greater then startdate */
SET #sqlTemp = NULL;
SET #sqlTemp =
CONCAT(
'SELECT rowNum,l.completed,l.next_completed,l.first_completed,startingDate,endingDate,Type,itemDifference,
''',startDateOriginal,''' AS oStartDate, ''',startDate,''' as startDate,
(time_to_sec(timediff(next_completed, completed)) / 3600)AS cHours,
CASE
WHEN (''',startDateOriginal,''' > ''',startDate,''' AND Type LIKE ''%Enable%'' AND rowNum = ''',minRow,''')
THEN (time_to_sec(timediff(next_completed, ''',startDateOriginal,''')) / 3600)
WHEN (DAYOFYEAR(completed) = DAYOFYEAR(''',startDate,'''))
THEN ''',xHours,'''
WHEN (''',endHoursNotNull,''' > ''',endHoursNull,''' AND next_completed > ''',endDate,''' )
THEN ((time_to_sec(timediff(''',endDate,''', completed))) / 3600)
ELSE coolingHours
END AS coolingHours,
isError,charge,totalTimeRange,
l.logId,databaseName,i.name,l.itemId,
CASE
WHEN (''',startDateOriginal,''' > ''',startDate,''' AND Type LIKE ''%Enable%'' AND rowNum = ''',minRow,''')
THEN (itemDifference*(time_to_sec(timediff(next_completed, ''',startDateOriginal,''')) / 3600))
WHEN (DAYOFYEAR(completed) = DAYOFYEAR(''',startDate,'''))
THEN (''',xHours,'''* itemDifference)
WHEN (''',endHoursNotNull,''' > ''',endHoursNull,''' AND next_completed > ''',endDate,''' )
THEN (itemDifference*((time_to_sec(timediff(''',endDate,''', completed))) / 3600))
ELSE kwDifference
END AS kwDifference,cost,
CASE
WHEN (''',startDateOriginal,''' > ''',startDate,''' AND Type LIKE ''%Enable%'' AND rowNum = ''',minRow,''')
THEN ((time_to_sec(timediff(next_completed, ''',startDateOriginal,''')) / 3600)* cost)
WHEN (DAYOFYEAR(completed) = DAYOFYEAR(''',startDate,'''))
THEN (''',xHours,''' * cost)
WHEN (''',endHoursNotNull,''' > ''',endHoursNull,''' AND next_completed > ''',endDate,''' )
THEN (((time_to_sec(timediff(''',endDate,''', completed))) / 3600) * cost)
ELSE costT
END AS costT,l.details,timeInSeconds
FROM tempTable3 l
inner join items i ON l.logId = i.logId AND i.name LIKE ''%KW PRE%''
WHERE l.itemId = ''',myItemId,'''
AND completed BETWEEN ''', startDate, ''' AND ''', endDate, '''
');
PREPARE stmtTemp FROM #sqlTemp;
EXECUTE stmtTemp;
DEALLOCATE PREPARE stmtTemp;
DROP TEMPORARY TABLE tempTable3;
END //
DELIMITER ;
I do know that is has to do with the last row of data and the next_completed being null
last rows of data
row Num completed next_completed first_completed starting Date ending Date
28 12/28/2013 6:30:35 PM 12/29/2013 12:07:19 AM 12/27/2013 11:22:54 PM 12/31/1969 10:00:00 PM 12/31/2013 10:00:00 PM
29 12/29/2013 12:07:19 AM 12/29/2013 8:56:58 AM 12/28/2013 6:30:35 PM 12/31/1969 10:00:00 PM 12/31/2013 10:00:00 PM
30 12/29/2013 8:56:58 AM 12/31/2013 11:27:40 PM 12/29/2013 12:07:19 AM 12/31/1969 10:00:00 PM 12/31/2013 10:00:00 PM
31 12/31/2013 11:27:40 PM (null) 12/29/2013 8:56:58 AM 12/31/1969 10:00:00 PM 12/31/2013 10:00:00 PM