Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have my database up and running and can do some basic selects using SQL Server 2017 Management Studio. The problem I'm running into now is a have a table that depending on the values within a row, a certain outcome is generated. I have the below code which currently works.
I'm running into issues what I try to reference Master_Status when I'm writing another case.
Basically I need do say if Master_Status is null after the first check then allow it to go into the second criteria, etc. Have about 10 outcomes I need to build this out for.
Is this possible? Should I be using reference tables?
EDIT
Below better represents my problem: I'm trying to loop through a bunch of critera to determine the end status of a sale. The sale can only have a unique status which is why I'd like to check if master_status is null.
WITH MasterStatus AS
(
SELECT
[Name]
,case WHEN saleDate is not Null then 'outcome1'
else NULL end as 'Master_Status'
,case when SaleSize is not NULL and Master_Status is Null then
'Outcome2'
else NULL end as 'Master_status'
from [AllNames]
)
select
[Name]
from MasterStatus where Master_Status is not null
Based on the current iteration of your query, it seems you're struggling with how CASE expressions work. Rather than trying to use multiple CASE expressions to assign values to the same column (which won't work), you need one CASE expression with multiple WHEN conditions.
WITH MasterStatus AS
(
SELECT
Name
,CASE
WHEN saleDate IS NOT NULL
THEN 'Outcome1'
WHEN SaleSize IS NOT NULL
THEN 'Outcome2'
--...
WHEN ColumnN IS NOT NULL
THEN 'OutcomeN'
ELSE NULL
END AS Master_Status
FROM
AllNames
)
SELECT
Name
FROM
MasterStatus
WHERE
Master_Status IS NOT NULL;
The WHEN conditions will be evaluated in order, and on the first WHEN that evaluates to TRUE, the corresponding THEN value will be assigned to the column alias, Master_Status.
What you have actually already works, I believe your case statement is just ALWAYS true (so Master_Status is always not null.
See below:
declare #allnames as table ([name] int);
insert into #allnames([name])
values (1),(0)
;WITH MasterStatus as (
select
[name]
,case WHEN [name] = 1 then 'outcome1'
else NULL end as 'Master_Status'
from #allnames
)
select
[name]
from MasterStatus where Master_Status is not null
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I want to select some records from a table with CASE option
like this
SELECT col1,col2,
CASE col2
WHEN '7c6014eb0000d37090d972c0ad2520f7' THEN 'xxxxx'
WHEN '5610d19400005469af3a78d225e11cb9' THEN 'aaaaa'
WHEN '31c08eb10000ye1aa51ff5a165246604' THEN 'bbbb'
WHEN '37e543fe00016d03007f6b304edfa94e' THEN 'ccccc'
WHEN '0ca1e79f0001zde1909b64c3d1246b80' THEN 'ddddd'
WHEN '25a14c480001g491c7284b0e107a39e7' THEN 'eeeee'
+500k line ....
END AS TargetAliasColumnName
FROM table
but the problem that i have a large script +500k record,
i got just( Command(s) completed successfully.
) :/
Update:
The hole script compile in the excute area, but after executing , i got just Command(s) completed successfully. my table name is ( account) in the table there are 2 columns ( user,password) in the table there are 1 milion records, i want to to select all these records in the table but with CASE password records
It,s better to create table and put all case value pair into table .
after you can use joins to achieve your goal.
The SQL is probably too big to compile. If you add the case values to a table you will be able to do what you want.
tbl_case
key_column, case_value
7c6014eb0000737090d972c0ad2520f7 xxxxx
SELECT table.key_value, tbl_case.case value
from table
join tbl_case on table.key_value = tbl_case.key_value; ----------
Try This ,
Create another table like this
CREATE TABLE [dbo].[Table_1](
[Col2] [nvarchar](50) NULL,
[CaseVal] [nchar](10) NULL
) ON [PRIMARY]
Insert all the Distinct data what you have. Then write a sql like below
SELECT b.Col1, b.Col2, a.CaseVal TargetAliasColumnName
FROM Table_1 a inner join [dbo].[Table1] b on
a.col2=b.Col2
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
create table t1 (col1 int);
Leave the table empty.
select isnull(col1,0) from t1;
I want to replace null with zeros in the above case. However, ISNULL() does not work if there are no records in the table. How can I get around this?
Maybe you can first test if the table is empty:
IF NOT EXISTS (select * from t1)
SELECT 0
ELSE select coalesce(col1,0) from t1;
Anyway, you should use COALESCE instead of ISNULL because it is standard SQL.
In case if you want to replace non existing value then surround another null check of mentioned select statement. like this
ISNULL(select isnull(col1,0) from t1,0)
COALESCE(col1, 0)
will give you the first non-NULL value from the list, which is
col1 if col1 does not contain NULL
0 if col1 contains NULL.
If no record exists in the table , your query returns EMPTY not NULL .
You can transform the EMPTY value into a NULL value and then switch it to 0 like this :
SELECT ISNULL((SELECT col1 FROM tl),0) AS col1;
When I want to return exactly one row from a table that might be empty or have an arbitrary number of rows, then I often use aggregation:
select coalesce(max(col1), 0)
from t1;
This is guaranteed to return exactly one row. It is unclear what you want when the table is not empty, however.
If you absolutely must have a value returned for an empty table, maybe something like:
if ((select COUNT(*) from t1) = 0)
begin
select 0 as col1;
end
else
begin
select isnull(col1,0) as col1 from t1;
end
The left join will get a hard coded table, OneZero, even with no rows in t1.
select isnull(t1.col1, OneZero.zero)
from ( values(0) ) as OneZero (zero)
left join t1
on 1 = 1
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have 2 tables: MainTable and ControlTable.
I want to write a query that builds a string representing a file path.
File path will be built dynamically depending on a query result between two tables.
Main table has the following columns:
ControlNumber
CustomerID
CustomerStatement
The Control table has only one column: ControlNumber
I need to write a query that checks if Main table has a ControlNumber defined in Control Table.
If there is a match, I append \FolderA to my FilePath
If no match, I append \FolderB
Ending result will be something like this:
C:\Customers\FolderA or C:\Customers\FolderB
I suspect I need to use left join
How can I do that?
You're right that you want a left join. Combine that with a case...when expression to determine the value:
select
*,
case
when Control.ControlNumber is not null
then '\FolderA'
else '\FolderB'
end as FilePath
from main
left join control on main.ControlNumber = control.ControlNumber
It's not clear where the rest of the path comes from; maybe it's static and you want to concatenate it with the value from the case expression:
'c:\customers' + -- or concat() or || depending on sql dialect
case when Control.ControlNumber is not null then '\FolderA' else '\FolderB' end as FilePath
SELECT 'C:\' || CustomerID || '\FolderA'
FROM MainTable
WHERE EXISTS
( SELECT 1 FROM ControlNumber WHERE ControlTable.ControlNumber = MainTable.CustomerID )
UNION
SELECT 'C:\' || CustomerID || '\FolderB'
FROM MainTable
WHERE NOT EXISTS
( SELECT 1 FROM ControlTable WHERE ControlTable.ControlNumber = MainTable.ControlNumber)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How do you return all possibilities, whether there is content or it is NULL?
If I want to return everything that isn't NULL:
SELECT * FROM table WHERE column LIKE '%'
And if I want to return all NULLs:
SELECT * FROM table WHERE column IS NULL
How do I combine them both? I need to be able to because I am parameterizing it. The front end of my application will have multiple options ALL (any content or NULL) or a specific value.
How can I achieve this?
EDIT:
Let me clarify better. I have a dropdown List that will show things like this
-Select All-
Team A
Team B
...
So if -Select All- is selected then I need the query to return all NULLs and those with any Team
If Team A is selected I need to show only Team A and no NULLs and so on...
I cant change the query just a single variable (parameter)
WHERE column LIKE '%' OR column IS NULL
Assuming NULL as the parameter value means "All"
WHERE Team = #Team OR #Team IS NULL
Unless you are on 2008+ and use OPTION (RECOMPILE) this can give sub optimal plans though.
See Dynamic Search Conditions in T-SQL
It's fairly straightforward. To only get NULLS:
SELECT * FROM table
WHERE column IS NULL
To only get NOT NULLS:
SELECT * FROM table
WHERE column IS NOT NULL
-- could be this if your example is not representative
-- WHERE column IS NULL OR column LIKE '%whatever%'
And for everything (no filter), just do:
SELECT * FROM table
Further clarification:
In your example, if the code is already written and you can only pass in the WHERE clause then you could do this:
WHERE <insert here>
column IS NULL -- just nulls
column = 'teamX' OR column IS NULL -- nulls or 'teamX'
column IS NOT NULL -- any value, but no nulls
1=1 -- for the case where you don't really want a WHERE clause. All records
It doesn't sound like this is the best way of structuring your code, but if you are already restricted by something that can't be changed, I guess you have to make do.
If I understood your question then this is what you are looking for
SELECT *
FROM table
WHERE column LIKE '%' or column Is null
Does select * from table get you what you want?
Perhaps you mean "parameter can be passed or parameter can be NULL" ?
If so then something like this should do the trick
SELECT * FROM table WHERE param IS NULL OR column LIKE '%' + param '%'
Similarly if parameter passed keyword 'ALL' that means "select everything" it would be
SELECT * FROM table WHERE param = 'All' OR column LIKE '%' + param '%'
One case is not to use any where clauses.
Or else you can use or condition
where (column is null or column like '%something%')
Try something like this:
SELECT * FROM table WHERE column LIKE '%'
Union
SELECT * FROM table WHERE column IS NULL
It will combine both query if they have the same column name and number, since the only difference is where clause, it should be working
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Case Order by using Null
I'm looking to get a list of records ordered by an "ordernum" field. The ordernum field is an int field. This field starts as NULL until set by a user. I would like the NULL entries to appear at the end of the list.
I am building a query as follows:
select *, case when (ordernum is null) then [largestInt] else ordernum end as newordernum
from tableName
order by newordernum
I know I could enter the value for the largest possible int for [largestInt], but I would like to replace [largestInt] with a variable. Is this possible?
I found a way to order NULL values on the bottom.
http://sqlblog.com/blogs/denis_gobo/archive/2007/10/19/3048.aspx
It meets my needs quite nicely. My query is now:
select *
from tableName
order by case when ordernum is null then 1 else 0 end, ordernum