Conditional Where statement syntax or some other solution - tsql

#MallUnit is a parameter with value 'Unit 401,Unit 402,Unit 403'
I would like to have a conditional where statement. Assume that before the AND there are other conditions that work just fine. Basically, if ScheduledMallUnitTypeID is null evaluate using the IN condition. Otherwise, use the like clause.
AND
CASE ScheduledMallUnitTypeID IS NULL THEN
ScheduledMallUnitTypeID IN
(
SELECT Value
FROM Toolbox.dbo.ReportingPortalMultiSetParameterFix(#MallUnit)
)
ELSE ScheduledMallUnitTypeID LIKE #MallUnit
END

This would work:
WHERE
( ScheduledMallUnitTypeID IS NULL AND
ScheduledMallUnitTypeID IN
(
SELECT Value
FROM Toolbox.dbo.ReportingPortalMultiSetParameterFix(#MallUnit)
)
)
OR
(
ScheduledMallUnitTypeID IS NOT NULL AND
ScheduledMallUnitTypeID LIKE #MallUnit
)

Related

Interconnecting tables on PostgreSQL

I am a newbie here.
I am using PostgreSQL to manipulate lots of data in my specific field of research. Unfortunately, I am encountering a problem that is not allowing me to continue my analysis. I tried to simplify my problem to clearly illustrate it.
Let's suppose I have a table called "Buyers" with those data:
table_buyers
The buyers can make ONLY ONE purchase in each store or none. There are three stores and there a table for each one. Just like below:
table_store1
table_store2
table_store3
To create the tables, I am using the following code:
CREATE TABLE public.buyer
(
ID integer NOT NULL PRIMARY KEY,
name text NOT NULL,
phone text NOT NULL
)
WITH (
OIDS = FALSE
)
;
CREATE TABLE public.Store1
(
ID_buyer integer NOT NULL PRIMARY KEY,
total_order numeric NOT NULL,
total_itens integer NOT NULL
)
WITH (
OIDS = FALSE
)
;
CREATE TABLE public.Store2
(
ID_buyer integer NOT NULL PRIMARY KEY,
total_order numeric NOT NULL,
total_itens integer NOT NULL
)
WITH (
OIDS = FALSE
)
;
CREATE TABLE public.Store3
(
ID_buyer integer NOT NULL PRIMARY KEY,
total_order numeric NOT NULL,
total_itens integer NOT NULL
)
WITH (
OIDS = FALSE
)
;
To add the information on the tables, I am using the following code:
INSERT INTO buyer (ID, name, phone) VALUES
(1, 'Alex', 88888888),
(2, 'Igor', 77777777),
(3, 'Mike', 66666666);
INSERT INTO Store1 (ID_buyer, total_order, total_itens) VALUES
(1, 87.45, 8),
(2, 14.00, 3),
(3, 12.40, 4);
INSERT INTO Store2 (ID_buyer, total_order, total_itens) VALUES
(1, 785.12, 7),
(2, 9874.21, 25);
INSERT INTO Store3 (ID_buyer, total_order, total_itens) VALUES
(2, 45.87, 1);
As all the tables are interconnected by buyer's ID, I wish I could have a query that generates an output just like this:
desired output table.
Please, note that if the buyer did not buy anything in a store, I must print '0'.
I know this is an easy task, but unfortunately, I have been failing on accomplish it.
Using the 'AND' logical operator, I tried the following code to accomplish this task:
SELECT
buyer.id,
buyer.name,
store1.total_order,
store2.total_order,
store3.total_order
FROM
public.buyer,
public.store1,
public.store2,
public.store3
WHERE
buyer.id = store1.id_buyer AND
buyer.id = store2.id_buyer AND
buyer.id = store3.id_buyer;
But, obviously, it just returned 'Igor' as this was the only buyer that have bought items on all three stores (print screen).
Then, I tried the 'OR' logical operator, just like the following code:
SELECT
buyer.id,
buyer.name,
store1.total_order,
store2.total_order,
store3.total_order
FROM
public.buyer,
public.store1,
public.store2,
public.store3
WHERE
buyer.id = store1.id_buyer OR
buyer.id = store2.id_buyer OR
buyer.id = store3.id_buyer;
But then, it returns 12 lines with wrong values (print screen).
Clearly, my mistake is about not considering that 'Buyers' don't have to on all three stores on my code. I just can't correct it on my own, can you please help me?
I appreciate a lot for an answer that can light up my way. Thanks a lot!
Tips about how I can search for this issue are very welcome as well!
Ok. I doubt that this is the final answer for you, but its a start
SELECT
buyer.id,
buyer.name,
COALESCE( gb_store1.total_orders, 0 ) as store1_total,
COALESCE( gb_store2.total_orders, 0 ) as store2_total,
COALESCE( gb_store3.total_orders, 0 ) as store3_total
FROM
public.buyer,
LEFT OUTER JOIN ( SELECT ID_buyer,
SUM( total_orders ) as total_orders,
SUM( total_itens ) as total_itens
FROM public.store1
GROUP BY ID_buyer ) gb_store1 ON gb_store1.id_buyer = buyer.id ,
LEFT OUTER JOIN ( SELECT ID_buyer,
SUM( total_orders ) as total_orders,
SUM( total_itens ) as total_itens
FROM public.store2
GROUP BY ID_buyer ) gb_store2 ON gb_store2.id_buyer = buyer.id ,
LEFT OUTER JOIN ( SELECT ID_buyer,
SUM( total_orders ) as total_orders,
SUM( total_itens ) as total_itens
FROM public.store3
GROUP BY ID_buyer ) gb_store3 ON gb_store3.id_buyer = buyer.id ;
So, this query has a couple elements should focus on. The subselects/groupby allow you to total within your subtables by ID_buyer. The LEFT OUTER JOIN make its so your query can still return a result, even if a subselect finds no matching record. Finally, the COALESCE allows you to return 0 when one of your totals is NULL (because the subselect found no match).
Hope this helps.

Where clause check parameter value return a field is NULL

I have a where clause like this:
Where m.Date_6 = Case When #IsCurrentRequest = 1 Then NULL Else m.Date_6 End
#IsCurrentRequest is a bit parameter. I want to check if #IsCurrentRequest = 1 then return m.Date_6 is NULL otherwise return 1. I know this won't work because m.Date_6 = NULL is not working. How do I fix? thanks!
I am not sure I understood correctly your question, but may be this condition is what you are looking for (without using CASE)?
WHERE #isCurrentRequest=1 AND m.date_6 IS NULL OR #isCurrentRequest=0
Anyway, when checking if a value is NULL, you can't use column_name=NULL, but you should use column_name IS NULL (as NULL is a "particular" value)
The = operator will return NULL if any of its operands is NULL, therefore your code will not work as intended.
Try something like this:
WHERE IIF( #IsCurrentRequest = 1, IIF( m.Date_6 IS NULL, 1, 0 ), 1)

COALESCE command issue in Hive

I am trying to run a hive query using COALESCE function to create a view. But it is throwing error like
cannot recognize input near '(' 'SELECT' 'realvalue' in expression specification
The query is given below. Please help and mention what is wrong in this.
CREATE VIEW IF NOT EXISTS exampledb.`ara_service` AS
SELECT T1.EntityId, T1.entityname AS EntityName,
T1.`xxx`,
T1.`yyy`,
COALESCE (T1.`aaa`, (SELECT `realvalue` FROM exampledb.`aba_service`
WHERE `id` = '333')) AS `CombinedValue`,
T1.`ddd`,
T1.`jjj`,
etc..
Please help. The error is in the usage of the select statement inside COALESCE .
NoViableAltException(231#[435:1: precedenceEqualExpression : ( ( LPAREN precedenceBitwiseOrExpression COMMA )=> precedenceEqualExpressionMutiple | precedenceEqualExpressionSingle );])
Thanks
if all you need is a default value, you could do
CREATE VIEW IF NOT EXISTS exampledb.`ara_service` AS
SELECT T1.EntityId, T1.entityname AS EntityName,
T1.`xxx`,
T1.`yyy`,
COALESCE (T1.`aaa`, def.`realvalue` ) AS `CombinedValue`,
T1.`ddd`,
T1.`jjj`,
FROM your_table T1
CROSS JOIN (
SELECT `realvalue`
FROM exampledb.`aba_service` WHERE `id` = '333') def

WHERE IN with composite keys and wildcards (postgres)

As an extension to this question, is it possible to incorporate wildcards with postgres?
E.g. Something like this (note the wildcard to select all entries where key_part_1 has a value of 'C'):
SELECT *
FROM table_name
WHERE (key_part_1, key_part_2) IN ( ('B',1), ('C',?) );
Is this possible, and if so, what's the syntax?
If key_part_2 can be anything, there is no need to test it.
SELECT *
FROM table_name
WHERE (key_part_1, key_part_2) IN ( ('B',1) )
OR key_part_1 IN('C' )
;
You can use the same column in IN clause(if both columns are not nullable):
SELECT *
FROM table_name
WHERE (key_part_1, key_part_2) IN ( ('B',1), ('C',key_part_2) );
So for second value pair only key_part_1='C' will be used because key_part_2=key_part_2 is always true.
WHERE (key_part_1, key_part_2) IN ( ('B',1), ('C',key_part_2) );
<=>
WHERE (key_part_1='B' AND key_part_2 = 1)
OR (key_part_1='C' AND key_part_2 = key_part_2);
If columns can be nullable you can wrap it with COALESCE(column_name, value) like:
SELECT *
FROM tab
WHERE (key_part_1, COALESCE(key_part_2,-1)) IN ( ('B',1),
('C',COALESCE(key_part_2,-1)) );
SqlFiddleDemo
Note that value used in COALESCE should be distinct for actual data to avoid colisions.

T-SQL where clause case statement

Need some small help with some SQL. I am using a VARCHAR value to determine in a case which logic to use in WHERE clause but I am having some issues writing this case statement.
where
(CASE WHEN #p_flag = 'ATA'
THEN (#p_start_ata IS NULL AND #p_end_ata IS NULL) OR (vso.poa_ata between #p_start_ata and #p_end_ata)
ELSE (#p_start_atd IS NULL AND #p_end_atd IS NULL) OR (vso.pol_atd between #p_start_atd and #p_end_atd)
)
Line 93 Incorrect syntax near the keyword 'IS'.
Its probably a minor error but its frustrating me. Maybe there is a better way of writing this? Thanks!
Like said before you can not use a case statement like you are doing it. So this might be a suggestion:
WHERE
(
#p_flag = 'ATA'
AND
(
(#p_start_ata IS NULL AND #p_end_ata)
OR (vso.poa_ata between #p_start_ata and #p_end_ata)
)
)
OR
(
NOT #p_flag = 'ATA'
AND
(
(#p_start_atd IS NULL AND #p_end_atd IS NULL)
OR (vso.pol_atd between #p_start_atd and #p_end_atd)
)
)
You can't use the CASE like that!
It's use to get values and not restrictions. Check this to view how to properly use CASE.
In your case you've to change your logic probably using IF's and making the wanted SELECT's.