Saturday, 23 April 2016

How to use SELECT...CASE to get customized column names in result ?


SELECT...CASE can be used to display different strings based on different values for a table column.

Syntax
SELECT
   CASE field
       WHEN value1 THEN newValue1
       WHEN value2 THEN newValue2
       ELSE defaultValue
   END
   as fieldAlias
   ...
FROM ...
WHERE ...


Example

SELECT
qry.date as Date_Time,

CASE qry.id_service
  WHEN 0 THEN 'Internet'
  WHEN 1 THEN 'TV'
  WHEN 2 THEN 'telephone'
  ELSE qry.id_service
END as Service_Name,

CASE qry.returnStatus
  WHEN 0 THEN 'Success'
  ELSE 'Failed'
END as Status,

qry.name as 'Name',

FROM 
(
  SELECT lp.date, lp.id_service, lp.returnStatus, u.name
  FROM logs lp, userinfos u
  WHERE u.id = lp.id_user
) AS qry

No comments:

Post a Comment

Note: only a member of this blog may post a comment.