我的SQL语法有问题,但我仍然是程序员,所以我不知道错误消息的含义。
这是我的代码:
set @csum = 0;
select b.nama as divisi, a.nama, a.tgl, a.act, a.L_mulai, a.L_selesai, a.tot_jam, a.ket, (CASE WHEN a.act = 'lembur' THEN @csum = @csum + a.tot_jam ELSE @csum = @csum - a.tot_jam ) as `total jam`
FROM tbl_rkp_lemburtj AS a
LEFT JOIN tbl_bagian AS b ON a.Divisi = b.id
WHERE a.nama = 'Rofiq'
order by a.id;
请告诉我该怎么做才能更正它。
这是我收到的错误消息:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ') as `total jam` FROM tbl_rkp_lemburtj AS a LEFT JOIN tbl_bagian AS b ON a.Div' at line 1
使用参数如果tom是lembur而不是加,则参数total总计tot_jam的总阻塞,否则,如果act是tj则减去
答案 0 :(得分:1)
使用此查询,您不需要variable
即可获得sum()
。
select b.nama, a.nama, a.tgl, a.act, a.L_mulai, a.L_selesai, a.tot_jam, a.ket
, sum(CASE WHEN a.act = 'lembur' THEN a.tot_jam ELSE 0 END) as `total jam`
FROM tbl_rkp_lemburtj AS a
LEFT JOIN tbl_bagian AS b ON a.Divisi = b.id
WHERE a.nama = 'Rofiq'
order by a.id;
答案 1 :(得分:0)
如果您要根据SUM()
语句中的逻辑来获取CASE
,则可以尝试如下操作:
SELECT b.nama, a.nama, a.tgl, a.act, a.L_mulai, a.L_selesai, a.tot_jam, a.ket,
SUM (
CASE
WHEN a.act = 'lembur' THEN a.tot_jam -- Add "tot_jam"
ELSE (-1) * a.tot_jam -- Subtract "tot_jam"
END
) AS total jam
FROM tbl_rkp_lemburtj AS a
LEFT JOIN tbl_bagian AS b ON a.Divisi = b.id
WHERE a.nama = 'Rofiq'
ORDER BY a.id
;
这将根据SUM()
内的评估表达式对所有行进行CASE
。因此,如果a.act = 'lember'
,则将tot_jam
加到总数上,否则将其减去。