CASE statement for checking a field value - sql

Hopefully you guy's can help.
I am writing a query from a table which has variable data specifically a completed column which can have a value of 1 or 3 the table also has two qty_ fields QTYORDERED and QTYSHIPPED
If the value is 3 in COMPLETED then QTYSHIPPED will contain a value and if the value is 1 the QTYORDERED will have a value.
What I need to do is within my query create one column which just has a QTY can someone show me how to achieve this in SQL Server

This is a simple case statement:
select (case when completed = 1 then QTYORDERED
when completed = 3 then QTYSHIPPED
end) as QTY
Note this will return NULL when completed has any other value.
You can also write this as:
select (case completed when 1 then QTYORDERED
when 3 then QTYSHIPPED
end)
However, the first form is more general, giving you more flexibility for complicated logic.

SELECT
CASE completed
WHEN 1 THEN QTYORDERED
WHEN 3 THEN QTYSHIPPED
ELSE 0 --Or add any logic when something goes wrong with "completed" value
END as Quantity
FROM ....

Related

SQL CASE WHEN Date

I am trying to create a table that gives me the number of users that have accessed an app within the last 3 months as follows:
last 3 months: (number)
last 2 months: (number)
last month: (number)
the number is coming from another table result that has the value day_p which indicates the day the unique user accessed the app. I just want to place them within the month frame. Below is the code I am trying to run, but I keep getting an error that name is expected, but I have named them as 'Three_Month', 'Two_Month', 'Last_Month'.
CREATE TABLE Last_Access AS
SELECT
count(CASE WHEN t1.day_p BETWEEN '20210518' AND '20210618' THEN 1 END) AS 'THREE_MONTH',
count(CASE WHEN t1.day_p BETWEEN '20210619' AND '20210718' THEN 1 END) AS 'TWO_MONTH',
count(CASE WHEN t1.day_p BETWEEN '20210719' AND '20210819' THEN 1 END) AS 'LAST_MONTH',
End
FROM Result AS t1;
Any suggestions / tips would be appreciated! :)
To create a TABLE you need to give your variables names. You could also attach a label to the variable if you wanted. You don't need to include the label= keyword, but I find it makes it clearer what the string is there for.
CREATE TABLE Last_Access AS
SELECT
count(CASE WHEN t1.day_p BETWEEN '20210518' AND '20210618' THEN 1 END)
AS THREE_MONTH LABEL='THREE_MONTH'
,count(CASE WHEN t1.day_p BETWEEN '20210619' AND '20210718' THEN 1 END)
AS TWO_MONTH LABEL='TWO_MONTH'
FROM Result AS t1
;
PS Don't put continuation characters at the end of the lines. Places them at the start of the line and you will be less likely to include an extra one like in your example because they will be more visible to the humans reading the code.

Using IF statement to pull boolean column header for an entry

I'm not good at all with IF statements. I currently have a schedule that looks like this:
Lot(Int) PartNum(Varchar50) Amount(Int) IsPainted(Bool) IsInspected(Bool) Finished(Bool)
1 xxx-0191 500 1 1 0
2 xxx-0191 700 1 0 0
What I'm trying to accomplish, and I'm under the thought it'll have to be handled by an IF statement but I'm certainly open for using whatever works best here, is to have a query that will give me the following
Lot PartNum Amount Status
1 xxx-0191 500 Inspected
2 xxx-0191 700 Painted
What I need it to do is just pull the last available column of "True" or "1" in the boolean columns and just display that information in the "Status" column in the query.
use this code
select
Lot,
PartNum,
Aamount,
Case when IsInspected=1 then 'Inspected' else 'Painted' end Status
from
table
Use case. Something like this:
select lot, partnum, amount,
(case when Finished = 1 then 'Finished'
when IsInspected = 1 then 'Inspected'
when IsPainted = 1 then 'Painted'
) as status
This chooses the last boolean as the one chosen for the status.

Qualifying a column in a SQL select statement

I'm looking to generate a query that pulls from several tables. Most are rather straightforward and I can pull a value from a table directly but there is one table that is pivoted so that the value I want depends on the value in another column.
The table looks like the below:
ID Condition Value
1 Stage1 6
2 Stage2 9
3 Stage3 5
4 Stage4 2
So I'm looking to write a query that essentially "qualifies" the value I want by telling the table which condition.
An example of my SQL:
Select Attribute1, Stage1Value, Stage2Value, Stage3Value
From attribute, stage
where attribute = project1
So I can't just pull the "Value" column as it needs to know which stage in the query.
There are 30 columns I am trying to pull - of which 13 fall into this category. Thanks for any help you can provide.
So, you want conditional aggregation something :
select a.<col>,
sum(case when s.Condition = 'Stage1' then s.value else 0 end),
. . .
sum(case when s.Condition = 'Stage4' then s.value else 0 end)
from attribute a inner join
stage s
on s.<col> = a.<col>
group by a.<col>

SQL-Server - Ability to pass subset parameter in the select?

I'm trying create a query that will output a total number, as well as a subset of the total number in SQL-Server. I can think of a way to do this via subqueries, but that seems like a ton of work. Is there a faster way to write this query?
Table name: orders
OrderID Date Type OrderSize
1 1/1/2012 Electronics $282.02
2 1/1/2012 Electronics $1,000.56
3 1/1/2012 Books $17.25
4 1/1/2012 Books $10.00
What I am trying to output would look like this:
Date ElectronicOrders ElectronicOrderSize BookOrders BookOrderSize
1/1/2012 2 $1,282.58 2 $27.25
I could create a temp table, then run 2 update queries - 1 WHERE Type = 'Electronics' and 1 WHERE Type = 'Books'.
What I have seen in some programming languages, such as R, is the ability to subset a variable. Is there a way for me to say something like:
count(OrderID, Type = 'Electronics) as ElectronicOrders, sum(OrderSize, Type = 'Electronics') as ElectronicOrderSize
Or am I stuck with subqueries and UPDATE queries?
I haven't ever gotten the new PIVOT syntax to make sense in my head but you can do a pivot table by grouping, and taking aggregate functions in a case statement.
select [date], sum( case when type = 'Electronics' then (ordersize) else 0 end) AS ElectronicsSum,
sum( case when type = 'Electronics' then 1 else 0 end) AS ElectronicsCount,
sum( case when type = 'Books' then (ordersize) else 0 end) AS BooksSum,
sum( case when type = 'Books' then 1 else 0 end) AS BooksCoumt
from orders
group by [date]
I put a fiddle thing up to test it out. If Aaron B. posts up a solution, give him the answer credit, I might not have even recognized the pivotyness of it.

My aggregate is not affected by ROLLUP

I have a query similar to the following:
SELECT CASE WHEN (GROUPING(Name) = 1) THEN 'All' ELSE Name END AS Name,
CASE WHEN (GROUPING(Type) = 1) THEN 'All' ELSE Type END AS Type,
sum(quantity) AS [Quantity],
CAST(sum(quantity) * (SELECT QuantityMultiplier FROM QuantityMultipliers WHERE a = t.b) AS DECIMAL(18,2)) AS Multiplied Quantity
FROM #Table t
GROUP BY Name, Type WITH ROLLUP
I'm trying to return a list of Names, Types, a summed Quantity and a summed quantity multiplied by an arbitrary number. All fine so far. I also need to return a sub-total row per Name and per Type, such as the following
Name Type Quantity Multiplied Quantity
------- --------- ----------- -------------------
a 1 2 4
a 2 3 3
a ALL 5 7
b 1 6 12
b 2 1 1
b ALL 7 13
ALL ALL 24 40
The first 3 columns are fine. I'm getting null values in the rollup rows for the multiplied quantity though. The only reason I can think this is happening is because SQL doesn't recognize the last column as an aggregate now that I've multiplied it by something.
Can I somehow work around this without things getting too convoluted?
I will be falling back onto temporary tables if this can't be done.
In your sub-query to acquire the multiplier, you have WHERE a=b. Are either a or b from the tables in your main query?
If these values are static (nothing to do with the main query), it looks like it should be fine...
If the a or b values are the name or type field, they can be NULL for the rollup records. If so, you can change to something similiar to...
CAST(sum(quantity * (<multiplie_query>)) AS DECIMAL(18,2)).
If a or b are other field from your main query, you'd be getting multiple records back, not just a single multiplier. You could change to something like...
CAST(sum(quantity) * (SELECT MAX(multiplier) FROM ...)) AS DECIMAL(18,2))