I have a query that goes something like this:
SELECT SUM(`table`.points) AS total_points FROM table
This will return something like this
| **points** |
324
Now I want to add another result next to it depending on the total points that the user has and display it. Below is the sample that I am trying to achieve
if (total_points >= 50 && < 100) {
//display another column next to the points
another_rows AS total_points + 50
} else if (total_points >= 100 && < 200) {
another_rows AS total_points + 100
} else if (total_points >= 200 && < 300) {
another_rows AS total_points + 200
} else if (total_points >= 300 || 300) {
another_rows AS total_points + 300
} else {
another_rows AS total_points
}
Desire results:
| **points** | **another_row** |
324 824
SQL has a construct called CASE
for these usecases exactly:
SELECT SUM(points) AS total_points,
SUM(points) +
CASE
WHEN SUM(points) BETWEEN 50 AND 100 THEN 50
WHEN SUM(points) BETWEEN 100 AND 200 THEN 100
WHEN SUM(points) BETWEEN 200 AND 300 THEN 200
WHEN SUM(points) BETWEEN 300 AND 400 THEN 300
ELSE 500
END AS another_row
FROM `table`
Use the CASE WHEN for this:
select SUM(`table`.points) AS total_points,
CASE SUM(`table`.points) AS total_points
WHEN total_points >= 50 AND total_points < 100 THEN
total_points + 50 AS another_row
WHEN total_points >= 100 AND total_points < 200 THEN
total_points + 100 AS AS another_row
WHEN total_points >= 200 AND total_points < 300 THEN
total_points + 200 AS AS another_row
WHEN total_points >= 300 AND total_points < 400 THEN
total_points + 300 AS AS another_row
ELSE
total_points + 500 AS AS another_row
END CASE
FROM `table`
SELECT SUM(`table`.points) AS total_points ,Case when (total_points>= 50 &&< 100)
then
another_rows AS total_points + 50
case
when (total_points >= 100 && total_points< 200) then
total_points + 100
case when (total_points >= 200 && total_points< 300)then
total_points + 200
case when (total_points >= 300 && total_points< 400)then
total_points + 300
else
total_points + 500
end as another_rows
From table
This is what you are looking for right?
SELECT
total_points,
CASE
WHEN
total_points > 100
AND
total_points < 200
THEN (total_points + 50)
WHEN
total_points > 200
AND
total_points < 300
THEN (total_points + 100)
END AS another_row
FROM
# from clause
WHERE
# where clause