Hi @Rizal Valry ,
As Tom said, the order in which SQL Server processes statements is different from the order in which statements are written.
The aliases named in the CTE can be used at every stage of the code, please refer to:
;WITH cte as(SELECT
pks.id,
pks.nomor,
pks.nasabah_code,
nasabah.nama,
FORMAT(pks.pks_date_start, 'dd-MM-yyyy') AS tglMulai,
FORMAT(pks.pks_date_end, 'dd-MM-yyyy') AS tglAkhir,
pks.file_doc,
DATEDIFF(DAY, pks.pks_date_end, GETDATE()) as selExp,
CASE
WHEN DATEDIFF(DAY, pks.pks_date_end, GETDATE()) < 0 THEN 'Akan Berakhir'
WHEN DATEDIFF(DAY, pks.pks_date_end, GETDATE()) = 0 THEN 'Berakhir'
WHEN DATEDIFF(DAY, pks.pks_date_end, GETDATE()) > 0 THEN 'Kadaluarsa'
END AS sts
FROM
vm.pks
INNER JOIN vm.nasabah
ON nasabah.code = pks.nasabah_code AND nasabah.record_code = '1'
WHERE
pks.record_code = '1' AND
(pks.nomor LIKE '%CBG%' OR
pks.nasabah_code LIKE '%BSP%' OR
nasabah.nama LIKE '%Bina San Prima%'))
SELECT * FROM cte
WHERE sts = 'Kadaluarsa' AND selExp >= '0'
ORDER BY selExp DESC
In addition, the HAVING clause is generally used with aggregate functions or GROUP BY clauses. So your code is best to use WHERE clause instead of HAVING clause.
If you have any question, please feel free to let me know.
Regards
Echo
If the answer is helpful, please click "Accept Answer" and upvote it.