I've run into a snag with an sqlite database I've been working on. Below is a simplified example of the problem.
Suppose I have the following table:
CREATE TABLE "prices" (
"id" INTEGER NOT NULL UNIQUE,
"name" TEXT NOT NULL UNIQUE,
"list_price" NUMERIC NOT NULL,
"sale_price" NUMERIC,
"tax_rate" NUMERIC NOT NULL,
PRIMARY KEY("id" AUTOINCREMENT)
);
Is there a way to do something like the following?
SELECT
name,
CASE
WHEN sale_price IS NULL
THEN list_price
ELSE sale_price
END AS price,
price * tax_rate AS tax
FROM prices;
The
tax
column doesn't seem to acknowledge the price
column's existence, presumably because it's a column in the query rather than the source table. I could re-implement the CASE
logic for the tax
field, but that feels inelegant and error-prone.Is there a better way to do this?
Shannon Prickett reshared this.
Isaac Ji Kuo
in reply to Jonathan Lamothe • • •Sensitive content
Probably not as elegant as you'd like, but:
SELECT tem.*,
price*tax_rate AS tax
FROM
(SELECT name,
CASE
WHEN sale_price IS NULL
THEN list_price
ELSE sale_price
END AS price
FROM prices) AS tem;
Jonathan Lamothe likes this.
Jonathan Lamothe
in reply to Isaac Ji Kuo • •Isaac Ji Kuo
in reply to Jonathan Lamothe • • •Sensitive content
Jonathan Lamothe
in reply to Isaac Ji Kuo • •If you're morbidly curious, the final resulting code was:
((( David "Kahomono" Frier )))
in reply to Jonathan Lamothe • • •Jonathan Lamothe
in reply to ((( David "Kahomono" Frier ))) • •@((( David "Kahomono" Frier ))) Yeah, that was my assumption. I just wasn't sure what the best way to go about fixing it was. So far, this is the front-runner:
Isaac Ji Kuo
2024-06-13 21:30:16
((( David "Kahomono" Frier )))
in reply to Jonathan Lamothe • • •Ryan Frame
in reply to Jonathan Lamothe • • •WITH
to do it in two steps:Blue Witch Gwen
in reply to Jonathan Lamothe • • •Sensitive content
But yeah, you have figured out why you can't do it. You're actually, imho, best off implementing the case in the tax column. Or changing how you handle sales.