nvl with query inside - sql

Its possible to do something like this:
and zmt.mediatypeid in nvl(:P21_MEDIA, select mediatypeid from zbx.media_type)
:P21_MEDIA is a variable

Yes, it is called a scalar subquery expression:
select x, (select y from another_table where foo = x) from the_table
select x from the_table where foo = (select y from another_table where bar = x)
It can only return a single column and a single row, anything else is an error.
I cannot test it right now, but I would assume you can also use it inside a function such as NVL. The documentation only mentions that it cannot be used in GROUP BY.

yes, you can use CASE statement to check the condition:
and 1 = CASE
WHEN :P21_MEDIA IS NOT NULL THEN
CASE
WHEN zmt.mediatypeid = :P21_MEDIA THEN 1
ELSE 0
END
WHEN zmt.mediatypeid IN (select mediatypeid from zbx.media_type) THEN 1
ELSE 0
END

Related

Using Alias in Where Clause

I have a very large case in my select statement, that ends as either 1 or 0, and has an alias name "x". I want to check if "x" = 1 in my WHERE statement, but I know that aliases cannot be used in the where statement. Is my only way of checking for this condition to include the original case statement in the WHERE clause?
You could use CROSS/OUTER APPLY:
SELECT *
FROM tab t
CROSS APPLY (SELECT CASE WHEN t.col ... THEN
-- very complex conditions
END
) sub(c)
WHERE sub.c = ?;
This approach allows you to avoid nested subqueries.
You can put your statement in a cte:
; with CTE as (Select .... as X from ...)
Select *
from CTE
where X = 1
How about even simpler? Your case expression is returning a bit. Seems to me that if you need a where clause there is no need to run the case expression more than once.
select MyReturn = 1
from SomeTable
where case with a whole bunch of logic end = 1
Or if you need it to be parameterized something like this.
select MyReturn = #MyBit
from SomeTable
where case with a whole bunch of logic end = #MyBit
Doesn't a subquery work just fine?
SELECT ST.*
FROM (SELECT TBL.*,
CASE WHEN ComplexCondition THEN 'Something'
ELSE 'SomethingElse'
END AS aliasedColumn
FROM SomeTable
) ST
WHERE ST.aliasedColumn = 'Something';

How to COUNT a value in a column?

I have a column where I flag two values (0 and 1). How can I select all from the table but only counting the value 1 from the flag column?
SQL Server
You need a COUNT with CASE expression, like this:
COUNT(CASE WHEN flag = 1 then 1 END)
If you want to return all of your values and also have a total count (using sort of logic) you could use a window function aggregation using over like so:
select
t.*
, count(case when flag = 1 then 1 end) over(partition by 1) as flag_1_count
from t
Err, are you asking how to perform a simple select statement or am I missing something...
Like this?
SELECT *
FROM [YourTableName]
WHERE FlagColumnName = 1
This should do it
Select count(0)
from YourTableName
where ValueField = 1
I think, you mean something like this:
SELECT COUNT(*) FROM [YOUR_TABLE] WHERE [FLAGCOLUMN] = 1;
Not quite sure I understand the question, but wouldn't it be something like:
SELECT * FROM your_table WHERE flag = 1

Return an INT from a Case statement

I am attempting to create a row called Flag that will keep a count of when Value is above 2. Later I will need to sum flag as a count.
I currently have:
CASE
WHEN Value > 2
THEN 1
ELSE 0
END AS 'Flag',
CASE
WHEN 'Flag' = 1
THEN 1
ELSE 0
END AS 'FollowedUpCorrectly'
I receive the error:
Conversion failed when converting the varchar value 'Flag' to data
type int.
How can I force the 1 or 0 to be an INT in order to do later math?
I've looked around and I can't seem to find a way that fits.
To be able to use previously created columns in the select, you'll need to use for example outer apply, with something like this:
select
*
from table1
outer apply (
select CASE WHEN Value > 2 THEN 1 ELSE 0 END AS Flag
) X
outer apply (
select CASE WHEN X.Flag = 1 THEN 1 ELSE 0 END AS FollowedUpCorrectly
) Y
Test this in SQL Fiddle
You could use CTE or a subquery to create a flag and then do your case statement as needed in the outer query like this:
;WITH q1
AS (
SELECT
col1
,col2
,col3
,CASE
WHEN Value > 2
THEN 1
ELSE 0
END AS 'Flag'
FROM your_table --change this to match your table and column name
)
SELECT q1.col1
,q1.col2
,q1.col3
,CASE
WHEN q1.Flag = 1
THEN 1
ELSE 0
END AS 'FollowedUpCorrectly'
FROM q1;
I might misunderstand what you are after.
CASE
WHEN Value > 2
THEN 1
ELSE 0
END AS 'Flag',
CASE
WHEN 'Flag' = 1
THEN 1
ELSE 0
END AS 'FollowedUpCorrectly'
If these two lines are in the same code block, 'Flag' is unknown in the second Case Statement.
Update: As Siyual has pointed out, Flag is a string literal. Try changing the name to something that is not a reserved word.
You are comparing a string ('Flag') to an int (1). Perhaps you meant to refer to the first case that you named 'Flag'. If so, try referring to it without using the single quotes. Then the analyzer will recognize it and accept it as an int, which it is. But 'Flag' is a string. Flag is an int.

CASE statement with IN in WHERE clause

I'm trying to create the following WHERE clause:
AND CASE #SomePRarmeter
WHEN 'this' THEN
user_id IN (SELECT * FROM dbo.func_Id1(#User))
WHEN 'that' THEN
user_id IN (SELECT user_id from dbo.func_Ids2(#OrgsForReporter)
END
But I'm getting an error: Incorrect syntax near the keyword 'IN' (in the first condition) , although separately both of those conditions work. What would be the correct way to make such a statement work?
Thanks!
Try
AND (
(#SomePRarmeter = 'this' AND user_id IN (SELECT * FROM dbo.func_Id1(#User)))
OR
(#SomePRarmeter = 'that' AND user_id IN user_id IN (SELECT user_id from dbo.func_Ids2(#OrgsForReporter)))
)
You are doing select * in a subquery. You need to return only one column:
(SELECT * FROM dbo.func_Id1(#User))
to this:
(SELECT YOUR_USER_ID_COLUMN FROM dbo.func_Id1(#User))
A case statement must result in a value, not an expression. So this won't work:
select case when 1=1 then 1 in (1,2,3) end
But this will work;
select case when 1=1 then 1 end
The value can be the result of a subquery. So one solution would be to rewrite the where clause like:
CASE #SomePRarmeter
WHEN 'this' THEN
(SELECT count() FROM dbo.func_Id1(#User) f where f.user_id = t.user_id))
WHEN 'that' THEN
(SELECT count() from dbo.func_Ids2(#OrgsForReporter) f where f.user_id = t.user_id))
END > 1
Now it returns the number of matching rows. You can then filter with case ... end > 1.
I'd break this out:
IF 'this'
SELECT
...
WHERE user_id IN (SELECT * FROM dbo.func_Id1(#User))
ELSE IF 'that'
SELECT
...
WHERE user_id IN (SELECT user_id from dbo.func_Ids2(#OrgsForReporter))
CASE ... END returns an expression, not a piece of literal SQL code. Rather than:
AND CASE foo WHEN bar THEN bla=ble END -- Wrong
... you have to use this:
AND bla = CASE foo WHEN bar THEN ble END -- Right
In your case, you can do something on this line:
-- Untested
AND (
(#SomePRarmeter='this' AND user_id IN (SELECT * FROM dbo.func_Id1(#User)))
OR (#SomePRarmeter='that' AND user_id IN (SELECT user_id from bo.func_Ids2(#OrgsForReporter))
)

How to count specific values in a table

I've a column that have 15 distinct values. I'd like to count how many there are of a few of them,
I've come up with e.g.
select a,COUNT(IFNULL(b != 1,NULL)),COUNT(IFNULL(b != 2,NULL)) from
mytable group by a
select a,SUM(CASE WHEN a = 1 THEN 1 ELSE 0)),SUM(CASE WHEN a = 2 THEN 1 ELSE 0)) from
mytable group by a
What's the best way of doing this ? (note, I need to pivot those values to columns,
a simple select a,b,count(*) from mytable where b=1 or b=2 group by a,b; won't do.)
Of the two methods suggested in the question, I recommend the second:
select a,
SUM(CASE WHEN b = 1 THEN 1 ELSE 0) b1,
SUM(CASE WHEN b = 2 THEN 1 ELSE 0) b2
from mytable
group by a
- as it is both simpler and (I think) easier to understand, and therefore to maintain. I recommend including column aliases, as they make the output easier to understand.
First of all you misunderstood the IFNULL function (you probably wanted IF). See the documentation http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html .
The second query you have in your question will give you what you want. But SUM(a=x) is more than sufficient. In MySQL true is equal to 1 and false is equal to 0.
have u try cross join?
select *
from (
select a, sum(...) as aSum
from mytable
where a...
group
by a
) as forA
cross join (
select b, sum(...) as bsum
from (
select *
from mytable
where b...
group
by b
)
) as forB;