MySQL Procedure error in server - mysql

I am getting this following error , the same code is not throwing any error in my local system.
MySQL said:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use
near 'GROUP_CONCAT(CASE WHEN atv.alid = 1906962 and atv.atrtid = 1
THEN concat(replac' at line 1
below i posted my code
BEGIN
SET
##group_concat_max_len = 1024 * 13;
SET
#sql3 = NULL;
SELECT
GROUP_CONCAT(
CONCAT(
'replace(format(SUM(CASE WHEN atv.alid = ',
b.alid,
' and atv.atrtid = 1 THEN concat((atv.amount) , "") when atv.alid =',
b.alid,
' and atv.atrtid = 2 then concat((atv.amount) , "") END),2), ", " , "") as ',
REPLACE
(
CONCAT('`',
TRIM(acl.name),
'`'),
'.',
't'
),
' , replace(format( SUM(case when atv.alid = ',
b.alid,
' and atv.atrtid = 2 then concat((atv.amount/',
b.value,
'*100),"") WHEN atv.alid = ',
b.alid,
' and atv.atrtid = 1 then concat((atv.amount/',
b.value,
'*100) , "") end),2), ", ","") as ',
REPLACE
(
CONCAT('`',
TRIM(acl.name),
'-value`'),
'.',
't'
)
)
)
INTO
#sql1
FROM
business_tax_profile b
LEFT JOIN
account_ledger acl ON(
acl.alid = b.alid AND acl.company_id = 19
)
WHERE
b.butaptid = 2 AND b.butapsid = 1 AND b.company_id = 19;
SELECT
GROUP_CONCAT(
CONCAT(
'replace(format(SUM(CASE WHEN atv.alid = ',
b.alid,
' and atv.atrtid = 1 THEN concat((atv.amount) , "") when atv.alid =',
b.alid,
' and atv.atrtid = 2 then concat((atv.amount) , "") END) , 2) , ", " , "") as ',
REPLACE
(
CONCAT('`',
TRIM(acl.name),
'`'),
'.',
't'
),
' , replace(format(SUM(case when atv.alid = ',
b.alid,
' and atv.atrtid = 2 then concat((atv.amount/',
b.value,
'*100),"") WHEN atv.alid = ',
b.alid,
' and atv.atrtid = 1 then concat((atv.amount/',
b.value,
'*100) , "") end),2) , ", " , "") as ',
REPLACE
(
CONCAT('`',
TRIM(acl.name),
'-value`'),
'.',
't'
)
)
)
INTO
#sql4
FROM
business_tax_sub_profile b
LEFT JOIN
account_ledger acl ON(
acl.alid = b.alid AND acl.company_id = 19
)
WHERE
b.butasuptid = 2 AND b.company_id = 19 AND b.butasupsid = 1;
SELECT
GROUP_CONCAT(
CONCAT(
'GROUP_CONCAT(CASE WHEN atv.alid = ',
c.alid,
' and atv.atrtid = 1 THEN concat(replace(format(atv.amount,2),", ","") , "") when atv.alid=',
c.alid,
' AND atv.atrtid = 2 then concat(replace(format(atv.amount , 2),", ","") , "") END) as `',
TRIM(ao.name),
'`'
)
)
INTO
#sql2
FROM
extra_charges c
LEFT JOIN
account_ledger ao ON(
ao.alid = c.alid AND ao.company_id = 19
)
WHERE
c.ectid = 2 AND c.company_id = 19 AND c.ecsid = 1;
SET
#sql3 = CONCAT(
'CREATE OR REPLACE ALGORITHM = UNDEFINED DEFINER = root#localhost SQL SECURITY DEFINER VIEW `purchase_invoice_tax_report_view_19` AS SELECT i.pinvid as pinvid, ROUND(i.total_tax_amount,2) AS `total_tax_amount1`, i.outlet_chkid,i.receive_date as receive_date, i.total_qty, replace(format(i.payable_amount,2),", ","") as payable_amount, replace(format((i.complete_amount -i.total_tax_amount),2) , ", " , "") as total_amount_before_tax, v.gstin, v.data as vendor_data, group_concat((case when atv.alid = 35 and atv.atrtid = 1 then concat(replace(format(atv.amount,2),", ","") , "") when atv.alid = 35 and atv.atrtid = 2 then concat(replace(format(atv.amount,2),", ",""), "") end) separator " ") as `round`,',
COALESCE(#sql1,
'"0"'),
',',
COALESCE(#sql4,
'"0"'),
',',
COALESCE(#sql2,
'"0"'),
', al.name as vendor_name , i.date, (CASE WHEN i.is_transportation IS NULL and is_expense = 0 THEN "Purchase" WHEN i.is_transportation IS NULL and is_expense > 0 THEN "Expense" WHEN i.is_transportation > 0 and is_expense >0 THEN "Transportation" ELSE "Purchase" END) as purchase_type,i.invoice_number ,(case when a.avtid = 3 then "Purchases" end) as voucher_type , a.avtid, i.pinvsid FROM purchase_invoice i LEFT JOIN account_transaction atv ON(atv.avid = i.avid and atv.company_id = 19) left join account_voucher a on (a.avid = atv.avid and a.company_id=19) LEFT join vendor v on (v.venid = i.venid and v.company_id = 19) LEFT join account_ledger al on(al.alid = v.alid and al.company_id = 19) where a.avsid = 1 and a.avtid = 3 and a.company_id = 19 group by i.pinvid'
);
PREPARE
stmt
FROM
#sql3;
EXECUTE
stmt;
DEALLOCATE
PREPARE
stmt;
END
is there any syntax error or anything else because the same code working fine in the local system ....

Related

Using an OnCalcField with a query

// accounts receivable
qAR.SQL.Clear;
qAR.SQL.Text := 'Select C.Lastname,C.Firstname,C.Address,C.City,C.State,C.Zip,' +
'C.Hercell,C.Hiscell,C.Phone,C.Code,' +
'I.Date,I.Clino,I.Date,I.ToBePaid,' +
'SUM(CASE when C.Clino = I.Clino then I.ToBePaid END) as nToBePaid,' +
'SUM(CASE when C.Clino = I.Clino and I.Date between :S0 and :E0 then I.ToBePaid END) as nCurrent,' +
'SUM(CASE when C.Clino = I.Clino and I.Date between :S1 and :E1 then I.ToBePaid END) as nOver30,' +
'SUM(CASE when C.Clino = I.Clino and I.Date between :S2 and :E2 then I.ToBePaid END) as nOver60,' +
'SUM(CASE when C.Clino = I.Clino and I.Date <= :E3 then I.ToBePaid END) as nOver90 ' +
'from Invoice I ' +
'join Client C on C.Clino = I.Clino ' +
'where I.Date <= :E ' +
'and I.ToBePaid <> 0 ' +
'and I.Active = true ' +
'and C.Code <> 1 ' +
'group by C.Clino ' +
'having nToBePaid > 0 ' +
'order by C.Lastname,C.Firstname';
qAR.ParamByName('S0').AsDate := dDate30 + 1;
qAR.ParamByName('E0').AsDate := dBillingDate;
qAR.ParamByName('S1').AsDate := dDate60 + 1;
qAR.ParamByName('E1').AsDate := dDate30;
qAR.ParamByName('S2').AsDate := dDate90 + 1;
qAR.ParamByName('E2').AsDate := dDate60;
qAR.ParamByName('E3').AsDate := dDate90;
qAR.ParamByName('E').AsDate := dBillingDate;
qAR.FieldDefs.Updated := false;
qAR.FieldDefs.Update;
oField := TBooleanField.Create( qAR );
oField.FieldKind := fkCalculated;
qAR.OnCalcFields := qARCalcFields;
qAR.DetailFields := 'Clino';
qAR.Open;
I have a calculated field Sel (boolean) define in this query. I want to click a button and have the Sel fields on all records to be set to TRUE and another button and have them all set to FALSE. What should the code of 1) the OnCalcField and 2) each of the buttons be?
Thanks,
Jim Sawyer

how to display the value fields in one line but separate

SELECT bio.nama_lengkap AS nama,bio.jenis_pegawai,bio.progdi,bio.jabatan as jabatan1,bio.cabang,bio.tahun,
GROUP_CONCAT(CASE WHEN tb_penilaian.id_user = tb_user.id_user THEN rata_rata END) AS nilai,
round (avg(rata_rata),2) as rata
FROM tb_biodata as bio
INNER JOIN tb_penilaian ON tb_biodata.id_biodata = tb_penilaian.id_biodata
INNER JOIN tb_user ON tb_penilaian.id_user = tb_user.id_user
WHERE tb_biodata.jenis_pegawai = 'Tenaga Kependidikan' and tb_penilaian.tahun='2020' and tb_biodata.cabang = 'Majapahit 605' GROUP BY nama'
SELECT ... ,
SUBSTRING_INDEX(GROUP_CONCAT(CASE WHEN tb_penilaian.id_user = tb_user.id_user THEN rata_rata END), ',', 1) AS nilai1,
SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(CASE WHEN tb_penilaian.id_user = tb_user.id_user THEN rata_rata END), ',', 2), ',', -1) AS nilai2,
SUBSTRING_INDEX(GROUP_CONCAT(CASE WHEN tb_penilaian.id_user = tb_user.id_user THEN rata_rata END), ',', -1) AS nilai3,
...
Alternatively:
SELECT bio.nama_lengkap AS nama,
bio.jenis_pegawai,
bio.progdi,
bio.jabatan as jabatan1,
bio.cabang,
bio.tahun,
CASE WHEN tb_penilaian.id_user = tb_user.id_user and numners.num = 1
THEN ANY_VALUE(rata_rata)
END AS nilai1,
CASE WHEN tb_penilaian.id_user = tb_user.id_user and numners.num = 2
THEN ANY_VALUE(rata_rata)
END AS nilai2,
CASE WHEN tb_penilaian.id_user = tb_user.id_user and numners.num = 3
THEN ANY_VALUE(rata_rata)
END AS nilai3,
round (avg(rata_rata),2) as rata
FROM tb_biodata as bio
INNER JOIN tb_penilaian ON tb_biodata.id_biodata = tb_penilaian.id_biodata
INNER JOIN tb_user ON tb_penilaian.id_user = tb_user.id_user
INNER JOIN (SELECT 1 num UNION SELECT 2 UNION SELECT 3) numbers
WHERE tb_biodata.jenis_pegawai = 'Tenaga Kependidikan'
and tb_penilaian.tahun='2020'
and tb_biodata.cabang = 'Majapahit 605'
GROUP BY nama'

Send sql email from two select results

I need help, I want to ask, I send emails in two SQL tables as a body of the email. However, when the first table has no results, sends a blank email to me, even though the results of the second table exists.
The problem is with #body = #html1
Thank you very much
IF EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[qdatum2]'))
DROP VIEW [dbo].[qdatum2]
GO
-- vytvorenie
CREATE VIEW qdatum2 AS
SELECT(A.Firma) AS FIRMA, A.ID, (A.OBEC) AS OBEC, (A.Ulice) AS Ulica, A.Obec2 as 'Obec dod.', A.Ulice2 AS 'Ulica dod.',
VP.IDS AS REGION,
CAST(SUM(CASE WHEN F.RelTpFak = 2 THEN -F.Kc2 ELSE F.Kc2 END) AS DECIMAL(36,2)) AS OBRAT, MAX(F.DATUM) AS MAXDATUM, MIN(F.DATUM) AS MINDATUM
FROM (StwPh_35760532_2015.dbo.AD as A INNER JOIN StwPh_35760532_2015.dbo.sVPULpol AS VP ON A.RefVPrRegion = VP.ID)
inner JOIN StwPh_35760532_2015.dbo.FA AS F ON A.ID = F.RefAD
WHERE DATEADD(MONTH, 6, F.Datum) > GETDATE()
GROUP BY A.ID, a.Firma, A.Obec, A.Ulice, A.Obec2, A.Ulice2, VP.IDS
union all
SELECT(AD.Firma) AS FIRMA, AD.ID, (AD.OBEC) AS OBEC, (AD.Ulice) AS Ulica, AD.Obec2 as 'Obec dod.', AD.Ulice2 AS 'Ulica dod.',
sVPULpol.IDS AS REGION,
CAST(SUM(CASE WHEN FA.RelTpFak = 2 THEN -FA.Kc2 ELSE FA.Kc2 END) AS DECIMAL(36,2)) AS OBRAT, MAX(FA.DATUM) AS MAXDATUM, MIN(FA.DATUM) AS MINDATUM
FROM (AD INNER JOIN sVPULpol ON AD.RefVPrRegion = sVPULpol.ID) inner JOIN FA ON AD.ID = FA.RefAD
WHERE DATEADD(MONTH, 6, FA.Datum) > GETDATE()
GROUP BY AD.ID, ad.Firma, ad.Obec, ad.Ulice,AD.Obec2,AD.Ulice2, sVPULpol.IDS
go
IF EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[qdatum1]'))
DROP VIEW [dbo].[qdatum1]
GO
-- vytvorenie
CREATE VIEW qdatum1 AS
select (AD.Firma) AS FIRMA, AD.ID, (AD.OBEC) AS OBEC, (AD.Ulice) AS Ulica, AD.Obec2 as 'Obec dod.', AD.Ulice2 AS 'Ulica dod.', qdatum2.REGION,
SUM(qdatum2.OBRAT) as OBRAT, max(qdatum2.MAXDATUM) as MAXDATUM, MIN(qdatum2.MINDATUM) AS MINDATUM
from AD INNER JOIN qdatum2 ON AD.ID = qdatum2.ID
group by ad.id, ad.Firma, ad.Obec, ad.Ulice, ad.Obec2, ad.Ulice2, qdatum2.region
go
IF EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[qdatum]'))
DROP VIEW [dbo].[qdatum]
GO
-- vytvorenie
CREATE VIEW qdatum AS
SELECT qDATUM1.*
FROM qdatum1
WHERE DATEADD(DAY, 30, qdatum1.MAXDATUM) < getdate()
and qdatum1.REGION like '%OR%'
and qdatum1.OBRAT > 50
GO
DECLARE #html varchar(max)
SET #html = '<html>'
+ '<H3><font id="Text" style="color: Green;">PREHLAD AKTIVNYCH ZAKAZNIKOV BEZ ODBERU ZA POSLEDNYCH 30 DNI </H3>'
+ '<table border="1" bordercolor="#3300FF" style="background-color:#DDF8CC" width="70%" cellpadding=3 cellspacing=3>'
+ '<tr><font color="Green"><th>Firma</th><th>Obec</th><th>Ulica</th><th>Obec dod.</th><th>Ulica dod.</th><th>Obrat v € za posledných 6 mesiacov</th><th>Posledna. Faktura</th>
</tr>' +
CAST (( SELECT
td = qdatum.FIRMA, ' ',
td = qdatum.OBEC, ' ',
td = CASE WHEN qdatum.Ulica IS NULL THEN '''' ELSE qdatum.Ulica END, ' ',
td = CASE WHEN qdatum.[Obec dod.] IS NULL THEN '''' ELSE qdatum.[Obec dod.] end , ' ',
td = CASE WHEN qdatum.[Ulica dod.] IS NULL THEN '''' ELSE qdatum.[Ulica dod.] END, ' ',
td = qdatum.OBRAT, ' ',
td = CONVERT(VARCHAR(11),qdatum.MAXDATUM, 106)
from StwPh_35760532_2016.dbo.qdatum
where qdatum.REGION like '%B1OR%'
order by qdatum.MAXDATUM
FOR XML PATH ('tr'),ELEMENTS
) AS VARCHAR(MAX))
+
'<table>'
DECLARE #html1 varchar(max)
SET #html1 = '<html>'
+ '<H3><font id="Text" style="color: Green;">PREHLAD KOMUNIKÁCIE SO ZÁKAZNÍKOM REGION B1OR </H3>'
+ '<table border="1" bordercolor="#3300FF" style="background-color:#DDF8CC" width="70%" cellpadding=3 cellspacing=3>'
+ '<tr><font color="Green"><th>Firma</th><th>Obec</th><th>Ulica</th><th>Obec dod.</th><th>Ulica dod.</th><th>Posledna navsteva</th><th>Posledne volanie</th></tr>' +
CAST( (SELECT
td = AD.Firma , ' ',
td = AD.Obec, ' ',
td = CASE WHEN AD.Ulice IS NULL THEN '''' ELSE AD.Ulice END, ' ',
td = CASE WHEN AD.Obec2 IS NULL THEN '''' ELSE AD.Obec2 END, ' ',
td = CASE WHEN AD.Ulice2 IS NULL THEN '''' ELSE AD.Ulice2 END, ' ',
td = CASE WHEN CONVERT(VARCHAR (11), AD.VPrnavsteva, 106) IS NULL THEN '''' ELSE CONVERT(VARCHAR (11), AD.VPrnavsteva, 106) END, ' ',
td = CASE WHEN CONVERT(VARCHAR(11), AD.VPrvolane, 106) IS NULL THEN '''' ELSE CONVERT(VARCHAR(11), AD.VPrvolane, 106) END
FROM StwPh_35760532_2016.dbo.AD INNER JOIN StwPh_35760532_2016.dbo.sVPULpol ON AD.RefVPrRegion = sVPULpol.ID
WHERE AD.VPrnavsteva < DATEADD(DAY, -30 , GETDATE()) AND AD.VPrvolane < DATEADD(DAY, -30 , GETDATE())
AND AD.RefAD IS NULL
AND sVPULpol.IDS like '%B1OR%'
ORDER BY VPrnavsteva DESC
FOR XML PATH ('tr'),ELEMENTS
) AS VARCHAR(MAX))
+
'</table>'
+ #html
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'LACI_ADMINISTRATOR',
--#recipients = 'emailxx',
#copy_recipients = 'emailxy',
--#blind_copy_recipients = 'emailxxy',
#subject ='B1OR report',
#body = #html1,
#body_format = 'HTML'
Try using this:
DECLARE #html varchar(max)
SET #html = '<html>'
+ '<H3><font id="Text" style="color: Green;">PREHLAD AKTIVNYCH ZAKAZNIKOV BEZ ODBERU ZA POSLEDNYCH 30 DNI </H3>'
+ '<table border="1" bordercolor="#3300FF" style="background-color:#DDF8CC" width="70%" cellpadding=3 cellspacing=3>'
+ '<tr><font color="Green"><th>Firma</th><th>Obec</th><th>Ulica</th><th>Obec dod.</th><th>Ulica dod.</th><th>Obrat v € za posledných 6 mesiacov</th><th>Posledna. Faktura</th>
</tr>' +
ISNULL(CAST (( SELECT
td = qdatum.FIRMA, ' ',
td = qdatum.OBEC, ' ',
td = CASE WHEN qdatum.Ulica IS NULL THEN '''' ELSE qdatum.Ulica END, ' ',
td = CASE WHEN qdatum.[Obec dod.] IS NULL THEN '''' ELSE qdatum.[Obec dod.] end , ' ',
td = CASE WHEN qdatum.[Ulica dod.] IS NULL THEN '''' ELSE qdatum.[Ulica dod.] END, ' ',
td = qdatum.OBRAT, ' ',
td = CONVERT(VARCHAR(11),qdatum.MAXDATUM, 106)
from StwPh_35760532_2016.dbo.qdatum
where qdatum.REGION like '%B1OR%'
order by qdatum.MAXDATUM
FOR XML PATH ('tr'),ELEMENTS
) AS VARCHAR(MAX)), '')
+
'<table>'
DECLARE #html1 varchar(max)
SET #html1 = '<html>'
+ '<H3><font id="Text" style="color: Green;">PREHLAD KOMUNIKÁCIE SO ZÁKAZNÍKOM REGION B1OR </H3>'
+ '<table border="1" bordercolor="#3300FF" style="background-color:#DDF8CC" width="70%" cellpadding=3 cellspacing=3>'
+ '<tr><font color="Green"><th>Firma</th><th>Obec</th><th>Ulica</th><th>Obec dod.</th><th>Ulica dod.</th><th>Posledna navsteva</th><th>Posledne volanie</th></tr>' +
ISNULL(CAST( (SELECT
td = AD.Firma , ' ',
td = AD.Obec, ' ',
td = CASE WHEN AD.Ulice IS NULL THEN '''' ELSE AD.Ulice END, ' ',
td = CASE WHEN AD.Obec2 IS NULL THEN '''' ELSE AD.Obec2 END, ' ',
td = CASE WHEN AD.Ulice2 IS NULL THEN '''' ELSE AD.Ulice2 END, ' ',
td = CASE WHEN CONVERT(VARCHAR (11), AD.VPrnavsteva, 106) IS NULL THEN '''' ELSE CONVERT(VARCHAR (11), AD.VPrnavsteva, 106) END, ' ',
td = CASE WHEN CONVERT(VARCHAR(11), AD.VPrvolane, 106) IS NULL THEN '''' ELSE CONVERT(VARCHAR(11), AD.VPrvolane, 106) END
FROM StwPh_35760532_2016.dbo.AD INNER JOIN StwPh_35760532_2016.dbo.sVPULpol ON AD.RefVPrRegion = sVPULpol.ID
WHERE AD.VPrnavsteva < DATEADD(DAY, -30 , GETDATE()) AND AD.VPrvolane < DATEADD(DAY, -30 , GETDATE())
AND AD.RefAD IS NULL
AND sVPULpol.IDS like '%B1OR%'
ORDER BY VPrnavsteva DESC
FOR XML PATH ('tr'),ELEMENTS
) AS VARCHAR(MAX)),'')
+
'</table>'
+ #html
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'LACI_ADMINISTRATOR',
--#recipients = 'emailxx',
#copy_recipients = 'emailxy',
--#blind_copy_recipients = 'emailxxy',
#subject ='B1OR report',
#body = #html1,
#body_format = 'HTML'
I added ISNULL on your CAST(SELECT) so that your variable will not turn to null if SELECT doesn't return data.

IF statement is not formatted correctly and not sure how to fix

I am trying to set the startDate of the query to fiirst_completed based on a set of 'if true' conditions. I am getting an error that the syntax is wrong.
I am open to suggestions on how to do this.
I am including the entire query that I am working with as well as the piece separately that is giving me trouble.
specific part of query that is throwing an error
SELECT
IF (coolingHours is null AND rowNum = min(rowNum) THEN ''',startDate,''':= first_completed END IF,
rowNum,l.logId,l.completed,l.next_completed,l.first_completed,
isError,charge,totalTimeRange,startingDate,endingDate,coolingHours,
databaseName,i.name,l.itemId, kwDifference, cost, 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, '''
Sample Data
row Num completed next_completed first_completed cooling Hours
10 11/27/2013 1:05:45 AM 11/29/2013 11:18:34 PM 11/25/2013 11:21:15 PM (null)
11 11/29/2013 11:18:34 PM 11/30/2013 7:37:45 PM 11/27/2013 1:05:45 AM 20.3197
12 11/30/2013 7:37:45 PM 11/30/2013 11:36:57 PM 11/29/2013 11:18:34 PM (null)
13 11/30/2013 11:36:57 PM 12/1/2013 6:52:19 PM 11/30/2013 7:37:45 PM 19.2561
Full query
DECLARE startDate VARCHAR (50);
DECLARE endDate VARCHAR (50);
DECLARE mylogID INT;
DECLARE myItemId varchar (50);
DECLARE myItemId2 varchar (50);
DECLARE xHours varchar (50);
SET startDate = FROM_UNIXTIME(fromDate/1000);
SET endDate = FROM_UNIXTIME(toDate/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%');
SET #sql = NULL;
SET #sql = CONCAT(
'CREATE TEMPORARY TABLE tempTable3 AS (SELECT
#row := #row + 1 AS rownum,
a.logId,
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'', ''US/Pacific'') AS startingDate,
CONVERT_TZ(''', endDate, ''', ''UTC'', ''US/Pacific'') AS endingDate,
((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
inner join items i ON l.logId = i.logId AND i.name LIKE ''%KW PRE%''
)order by L1.completed');
SET #sqlTemp = NULL;
SET #sqlTemp = CONCAT(
'SELECT
IF (coolingHours is null AND rowNum = min(rowNum) THEN ''',startDate,''':= first_completed END IF,
rowNum,l.logId,l.completed,l.next_completed,l.first_completed,
isError,charge,totalTimeRange,startingDate,endingDate,coolingHours,
databaseName,i.name,l.itemId, kwDifference, cost, 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 stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
PREPARE stmtTemp FROM #sqlTemp;
EXECUTE stmtTemp;
DEALLOCATE PREPARE stmtTemp;
DROP TEMPORARY TABLE tempTable3
an inline IF is in this format IF (condition,truevalue,falsevalue) there's no THEN or END IF
try IF (coolingHours is NULL AND rowNum = min(rowNum),first_completed,",startDate,"),

SQL / Coalesce - Wrong row name

I have a problem with the request below!
REQUEST:
SELECT COALESCE(date(date_field), 'Total') AS "date_field_group",
COUNT( id_field ) AS "Nombre de bookings",
CONCAT( REPLACE( REPLACE( FORMAT( SUM( price1 ) , 2 ) , ',', ' ' ) , '.', ',' ) , ' €' ) AS "Total à l'achat",
CONCAT( REPLACE( REPLACE( FORMAT( SUM( price2 ) , 2 ) , ',', ' ' ) , '.', ',' ) , ' €' ) AS "Total à la vente",
CONCAT( REPLACE( REPLACE( FORMAT( SUM( price2 ) - SUM( price1 ) , 2 ) , ',', ' ' ) , '.', ',' ) , ' €' ) AS 'Marge',
CONCAT( REPLACE( FORMAT( (SUM( price2 ) / SUM( price1 ) ) , 2 ) , '1.', '' ) , ' ', '%') AS "Markup moyen"
FROM table1 S, table2 B
WHERE status_field
IN ( "1", "5")
AND DATE( date_field ) BETWEEN "2011-08-01" AND "2011-08-31"
AND type_field = "H"
AND price1 IS NOT NULL
AND S.id_field = B.id_field
AND B.id2 = "1"
GROUP BY date_field_group WITH ROLLUP
The thing is that the request is working fine (right numbers), but in the last line I was expected to get in first row "Total" and instead of that I got a field NULL...
Is someone know what is wrong with my request ?
Thx for any help ;).
You're query is almost correct (except for using implicit SQL '89 joins, which is an SQL anti-pattern)
The problem is in the last line: GROUP BY ... WITH ROLLUP.
The rollup gets applied very late in the process, after your COALESCE(date(date_field), 'Total').
So the coalesce has already finished by the time rollup comes along you need to rewrite the query like so:
SELECT COALESCE(date_field_group, 'Total') as date_field_group
, `Nombre de bookings`
, `Total à l'achat`
, `Total à la vente`
, `Marge`
, `Markup moyen`
FROM (
SELECT date(date_field) AS "date_field_group",
COUNT( id_field ) AS "Nombre de bookings",
CONCAT( REPLACE( REPLACE( FORMAT( SUM( price1 ) , 2 ) , ',', ' ' ) , '.', ',' ) , ' €' ) AS "Total à l'achat",
CONCAT( REPLACE( REPLACE( FORMAT( SUM( price2 ) , 2 ) , ',', ' ' ) , '.', ',' ) , ' €' ) AS "Total à la vente",
CONCAT( REPLACE( REPLACE( FORMAT( SUM( price2 ) - SUM( price1 ) , 2 ) , ',', ' ' ) , '.', ',' ) , ' €' ) AS 'Marge',
CONCAT( REPLACE( FORMAT( (SUM( price2 ) / SUM( price1 ) ) , 2 ) , '1.', '' ) , ' ', '%') AS "Markup moyen"
FROM table1 S
INNER JOIN table2 B ON (S.id_field = B.id_field)
WHERE status_field IN ( "1", "5")
AND DATE( date_field ) BETWEEN "2011-08-01" AND "2011-08-31"
AND type_field = "H"
AND price1 IS NOT NULL
AND B.id2 = "1"
GROUP BY date_field_group WITH ROLLUP ) AS subquery