Fix Caption column which is dependent on other Flags? - sql

I am trying to populate caption column depending on other flags and I am using case statement to achieve this. Unfortunately I am encountering problem with result. Caption should be same for each primary irrespective of Detail Flag.
Code:
SELECT Primary_Key, Detail_Flag, Flag_A, Flag_B,
CASE WHEN Detail_Flag=0 THEN
CASE WHEN Flag_A=1 AND Flag_B=1 THEN 1
ELSE 0 END
END AS IsCommercialFlag,
CASE WHEN Flag_A=1 AND Flag_B=1 THEN 'Yes'
ELSE 'No'
END
AS IsCommercialFlagCaption
FROM TableFlags
WHERE Primary_Key IN (123, 456)
ORDER BY Primary_Key, Detail_Flag
Actual Result:
Expected Result:

It seems you just need NULL handling. Considering you are currently using ORACLE as your DBMS product, You may try below query -
SELECT
Primary_Key,
Detail_Flag,
Flag_A,
Flag_B,
CASE WHEN Detail_Flag=0 THEN
CASE WHEN NVL(Flag_A, 1) = 1 AND NVL(Flag_B, 1) = 1 THEN 1
ELSE 0 END
END AS IsCommercialFlag,
CASE WHEN NVL(Flag_A, 1) = 1 AND NVL(Flag_B, 1) = 1 THEN 'Yes'
ELSE 'No'
END
AS IsCommercialFlagCaption
FROM TableFlags
WHERE Primary_Key IN (123, 456)
ORDER BY Primary_Key, Detail_Flag
If you are using MySQL, just replace NVL with IFNULL, For SQL SERVER user ISNULL.

You seem to want window functions:
SELECT Primary_Key, Detail_Flag, Flag_A, Flag_B,
(CASE WHEN Detail_Flag = 0 AND Flag_A = 1 AND Flag_B = 1
THEN 1
WHEN Detail_Flag = 0
THEN 0
END) AS IsCommercialFlag,
(CASE WHEN MAX(Flag_A) OVER (PARTITION BY Primary_Key) = 1 AND
MAX(Flag_B) OVER (PARTITION BY Primary_Key) = 1
THEN 'Yes'
ELSE 'No'
END) AS IsCommercialFlagCaption
FROM TableFlags
WHERE Primary_Key IN (123, 456)
ORDER BY Primary_Key, Detail_Flag;
You also seem to have no understanding of what "primary key" means in a database. It is unique meaning that the values are not repeated. I strongly advise you to not use such a name for a column that does have repeated values.

Here's the answer I was looking out.
SELECT Primary_Key, Detail_Flag, Flag_A, Flag_B,
CASE WHEN Detail_Flag=0 THEN
CASE WHEN Flag_A=1 AND Flag_B=1 THEN 1
ELSE 0 END
END AS IsCommercialFlag,
CASE WHEN SUM(Flag_A) over (Order by PrimaryKey) = 1 AND
SUM(Flag_B)over (Order by PrimaryKey) = 1 THEN 'Yes'
ELSE 'No'
END
AS IsCommercialFlagCaption
FROM TableFlags
WHERE Primary_Key IN (123, 456)
ORDER BY Primary_Key, Detail_Flag

Related

sql case statement IN with group by

I have a 2 column table with the columns : "user_name" and "characteristic". Each user_name may appear multiple times with a different characteristic.
The values in characteristic are:
Online
Instore
Account
Email
I want to write a sql statement that goes like this - but obviously this isn't working:
SELECT user_name,
case
when characteristic in ("online","instore") then 1
else 0
END as purchase_yn,
case
when characteristic in ("online","instore") and
characteristic in ("email",'account') then 1
else 0
END as purchaser_with_account
FROM my_table
GROUP BY user_name;
Essentially the first is a flag where I check for the presence of either value for that user_name.
The Second field is that they meet this criteria AND that they meet the criteria for having either 'email' or 'account'
An example the structure of your data would help better understand what you are trying to accomplish. But I think I get what you are trying to do.
You have to use an aggregate function in order to use a group by.
Something like SUM or AVG.
But you need first to build a pivot of your data and then you could use that pivot to check for your criterias:
This would create a table pivot that shows for each record what criterias are met:
SELECT
user_name,
case when characteristic = "online" then 1 else 0 end as online_yn,
case when characteristic = "instore" then 1 else 0 end as instore_yn,
case when characteristic = "account" then 1 else 0 end as account_yn,
case when characteristic = "email" then 1 else 0 end as email_yn,
FROM my_table
Now what you might wanted to do is to create an averaged version of these entries grouped by user_name and use those averages to create the fields you wanted. For that you need to use the same statement created earlier as an inline table :
Select
user_name,
case when avg(online_yn + instore_yn) >= 1 then 1 else 0 end as purchase_yn,
case when avg(online_yn + instore_yn) >= 1 and avg(email_yn + account_yn) >= 1 then 1 else 0 end as purchaser_with_account
From
(SELECT
user_name,
case when characteristic = "online" then 1 else 0 end as online_yn,
case when characteristic = "instore" then 1 else 0 end as instore_yn,
case when characteristic = "account" then 1 else 0 end as account_yn,
case when characteristic = "email" then 1 else 0 end as email_yn,
FROM my_table) avg_table
group by
user_name;
This should help.
It may not be efficient in terms of performance but you'll get what you want.
You just have to enclose the CASE expressions in COUNT aggregates:
SELECT user_name,
COUNT(case when characteristic in ("online","instore") then 1 END) as purchase_yn,
COUNT(case when characteristic in ("email",'account') then 1 END) as user_with_account
FROM my_table
GROUP BY user_name
If purchase_yn > 0 then you first flag is set. If purchase_yn > 0 and user_with_account > 0 then you second flag is set as well.
Note: You have to remove ELSE 0 from the CASE expressions because COUNT takes into account all not null values.
You haven't mentioned a specific RDBMS, but if SUM(DISTINCT ...) is available the following is quite nice:
SELECT
username,
SUM(DISTINCT
CASE
WHEN characteristic in ('online','instore') THEN 1
ELSE 0
END) AS purchase_yn,
CASE WHEN (
SUM(DISTINCT
CASE
WHEN characteristic in ('online','instore') THEN 1
WHEN characteristic in ('email','account') THEN 2
ELSE 0 END
)
) = 3 THEN 1 ELSE 0 END as purchaser_with_account
FROM
my_table
GROUP BY
username
If I correctly understand, if user have 'online' or 'instore', then for this user you want 1 as purchase_yn column, and if user also have 'email' or 'account', then 1 as purchaser_with_account column.
If this is correct, then one way is:
with your_table(user_name, characteristic) as(
select 1, 'online' union all
select 1, 'instore' union all
select 1, 'account' union all
select 1, 'email' union all
select 2, 'account' union all
select 2, 'email' union all
select 3, 'online'
)
-- below is actual query:
select your_table.user_name, coalesce(max(t1.purchase_yn), 0) as purchase_yn, coalesce(max(t2.purchaser_with_account), 0) as purchaser_with_account
from your_table
left join (SELECT user_name, 1 as purchase_yn from your_table where characteristic in('online','instore') ) t1
on your_table.user_name = t1.user_name
left join (SELECT user_name, 1 as purchaser_with_account from your_table where characteristic in('email', 'account') ) t2
on t1.user_name = t2.user_name
group by your_table.user_name

Case SQL If there is no record between dates

I'm new to SQL and am struggling with a case.
I would like to make the case where if an account (account_ID) doesn't have a record (ON billing_id) between current_date-302 and current_date-62 THEN MARK WITH A "1"
Query below:
Thanks in advance
SELECT
billing_date_local_time
,account_id
,contract_owner_name
,date_first_feature_partner
,deal_starts_at
,contract_id
,new_partner_type
,sum(voucher_sold) AS Vouchers
,sum(gross_bookings_local) AS GB
,sum(gross_revenue_local) AS GR
,is_G2
,Case when billing_date_local_time between current_date-302 and current_date-62 = 0 THEN 'YES' ELSE 'NO' End
FROM EMEA_ANALYTICS.eu_deal_flat
WHERE
country_id = 206
and billing_date_local_time between current_date-400
and current_date-2
GROUP BY 1,2,3,4,5,6,10,11
You'll need to do a correlated subquery; something like this:
select
a.billing_date_local_time
,a.account_id
,...
, CASE WHEN EXISTS (SELECT * FROM EMEA_ANALYTICS.eu_deal_flat b WHERE a.account_id = b.account_id AND b.billing_date_local_time between current_date-302 and current_date-62 ) THEN 'YES' ELSE 'NO' END
from
FROM EMEA_ANALYTICS.eu_deal_flat a
WHERE ...
You need to apply an aggregate function like this:
min(case when billing_date_local_time
between current_date-302 and current_date-62
then 0
else 1
end)

Getting a sum of only the first instance of a column in a sql query

I have the following SQL code:
SELECT EmployeeID,
SUM(CASE
WHEN Error1 = '0'
THEN 1
ELSE 0
END + CASE
WHEN Error2 = '0'
THEN 1
ELSE 0
END + CASE
WHEN Error3 = '0'
THEN 1
ELSE 0
END) AS TotalErrors
FROM SubmittedDocuments
GROUP BY EmployeeID
The statement should calculate the number of errors in the table for each employee. However, there is another column in the table SubmittedDocuments named "DocumentName". How could I write a statement that only counts errors for the first instance of each DocumentName? (Or only counts for the one with the lowest "SubmittedID", the unique identifier)
Sorry if anything in unclear, I will attempt to clear up any confusion in the comments.
I might have not got this right from your question, but I think this should work. If you could show some sample data and expected output then we can definitely have a sure answer.
SELECT EmployeeID
SUM(CASE WHEN DocIDErr > 1 THEN 0 ELSE 1 END)
FROM
(SELECT EmployeeID
, Error1
, ROW_NUMBER() OVER (PARTITION BY EmployeeID ORDER BY DocumentName) AS DocIDErr
FROM SubmittedDocuments) AS RS
GROUP BY EmployeeID
I don't think you want aggregation. I think you just want to select the first document for each name.
If so, this may be what you want:
select sd.*,
((case when error1 = '0' then 1 else 0 end) +
(case when error2 = '0' then 1 else 0 end) +
(case when error3 = '0' then 1 else 0 end)
) as numerrors
from (select sd.*,
row_number() over (partition by documentname order by submittedid) as seqnum
from SumittedDocuments sd
) sd
where seqnum = 1;

SQL - Command to get Id's with unique flags from multiple flags

ID Risk_1 Risk_2 Risk_3 Risk_4
XYZ Yes Yes Yes
ABC Yes
PQR Yes Yes
As you can see from the above table There are IDs that have multiple risks associated with them. I want to get an output of IDs where only one risk is associated with them.
In the case above I want all IDs which have only risk_1 so the result should be ABC.
How can I get this done using SQL?
Assuming that Risks are nullable.
SELECT ID
FROM tableName
WHERE CASE WHEN Risk_1 IS NOT NULL THEN 1 ELSE 0 END +
CASE WHEN Risk_2 IS NOT NULL THEN 1 ELSE 0 END +
CASE WHEN Risk_3 IS NOT NULL THEN 1 ELSE 0 END +
CASE WHEN Risk_4 IS NOT NULL THEN 1 ELSE 0 END = 1
SQLFiddle Demo
if however they are empty string,
SELECT ID
FROM tableName
WHERE CASE WHEN Risk_1 <> '' THEN 1 ELSE 0 END +
CASE WHEN Risk_2 <> '' THEN 1 ELSE 0 END +
CASE WHEN Risk_3 <> '' THEN 1 ELSE 0 END +
CASE WHEN Risk_4 <> '' THEN 1 ELSE 0 END = 1
SQLFiddle Demo
That will work with NULLs, empty strings, or values other than Yes (e.g. No)
SELECT ID
FROM Table1
WHERE COALESCE(Risk_1, 'No') = 'Yes' AND
COALESCE(Risk_2, 'No') <> 'Yes' AND
COALESCE(Risk_3, 'No') <> 'Yes' AND
COALESCE(Risk_4, 'No') <> 'Yes'
sqlfiddle
If the value of risks are only 'Yes' then below query will work
select ID from table where risk1||risk2||risk3||risk4='Yes'
If the value of risks are only 'Yes' and the empty risks have spaces instead of nulls then below query will work
select ID from table where replace(risk1||risk2||risk3||risk4,' ','')='Yes'
If you altered your schema so your table had columns ID and risk_type with a row for each risk type, you could have a query like this:
SELECT ID
FROM Table1
GROUP BY ID
HAVING COUNT(*) = 1
SQLFiddle
re-edit: modified to no longer specify which one risk type they have

How do I perform an IF...THEN in an SQL SELECT?

How do I perform an IF...THEN in an SQL SELECT statement?
For example:
SELECT IF(Obsolete = 'N' OR InStock = 'Y' ? 1 : 0) AS Saleable, * FROM Product
The CASE statement is the closest to IF in SQL and is supported on all versions of SQL Server.
SELECT CAST(
CASE
WHEN Obsolete = 'N' or InStock = 'Y'
THEN 1
ELSE 0
END AS bit) as Saleable, *
FROM Product
You only need to use the CAST operator if you want the result as a Boolean value. If you are happy with an int, this works:
SELECT CASE
WHEN Obsolete = 'N' or InStock = 'Y'
THEN 1
ELSE 0
END as Saleable, *
FROM Product
CASE statements can be embedded in other CASE statements and even included in aggregates.
SQL Server Denali (SQL Server 2012) adds the IIF statement which is also available in access (pointed out by Martin Smith):
SELECT IIF(Obsolete = 'N' or InStock = 'Y', 1, 0) as Saleable, * FROM Product
The case statement is your friend in this situation, and takes one of two forms:
The simple case:
SELECT CASE <variable> WHEN <value> THEN <returnvalue>
WHEN <othervalue> THEN <returnthis>
ELSE <returndefaultcase>
END AS <newcolumnname>
FROM <table>
The extended case:
SELECT CASE WHEN <test> THEN <returnvalue>
WHEN <othertest> THEN <returnthis>
ELSE <returndefaultcase>
END AS <newcolumnname>
FROM <table>
You can even put case statements in an order by clause for really fancy ordering.
From SQL Server 2012 you can use the IIF function for this.
SELECT IIF(Obsolete = 'N' OR InStock = 'Y', 1, 0) AS Salable, *
FROM Product
This is effectively just a shorthand (albeit not standard SQL) way of writing CASE.
I prefer the conciseness when compared with the expanded CASE version.
Both IIF() and CASE resolve as expressions within a SQL statement and can only be used in well-defined places.
The CASE expression cannot be used to control the flow of execution of
Transact-SQL statements, statement blocks, user-defined functions, and
stored procedures.
If your needs can not be satisfied by these limitations (for example, a need to return differently shaped result sets dependent on some condition) then SQL Server does also have a procedural IF keyword.
IF #IncludeExtendedInformation = 1
BEGIN
SELECT A,B,C,X,Y,Z
FROM T
END
ELSE
BEGIN
SELECT A,B,C
FROM T
END
Care must sometimes be taken to avoid parameter sniffing issues with this approach however.
You can find some nice examples in The Power of SQL CASE Statements, and I think the statement that you can use will be something like this (from 4guysfromrolla):
SELECT
FirstName, LastName,
Salary, DOB,
CASE Gender
WHEN 'M' THEN 'Male'
WHEN 'F' THEN 'Female'
END
FROM Employees
Use CASE. Something like this.
SELECT Salable =
CASE Obsolete
WHEN 'N' THEN 1
ELSE 0
END
SELECT
(CASE
WHEN (Obsolete = 'N' OR InStock = 'Y') THEN 'YES'
ELSE 'NO'
END) as Salable
, *
FROM Product
Microsoft SQL Server (T-SQL)
In a select, use:
select case when Obsolete = 'N' or InStock = 'Y' then 'YES' else 'NO' end
In a where clause, use:
where 1 = case when Obsolete = 'N' or InStock = 'Y' then 1 else 0 end
From this link, we can understand IF THEN ELSE in T-SQL:
IF EXISTS(SELECT *
FROM Northwind.dbo.Customers
WHERE CustomerId = 'ALFKI')
PRINT 'Need to update Customer Record ALFKI'
ELSE
PRINT 'Need to add Customer Record ALFKI'
IF EXISTS(SELECT *
FROM Northwind.dbo.Customers
WHERE CustomerId = 'LARSE')
PRINT 'Need to update Customer Record LARSE'
ELSE
PRINT 'Need to add Customer Record LARSE'
Isn't this good enough for T-SQL?
SELECT
CASE
WHEN OBSOLETE = 'N' or InStock = 'Y' THEN 'TRUE'
ELSE 'FALSE'
END AS Salable,
*
FROM PRODUCT
Simple if-else statement in SQL Server:
DECLARE #val INT;
SET #val = 15;
IF #val < 25
PRINT 'Hi Ravi Anand';
ELSE
PRINT 'By Ravi Anand.';
GO
Nested If...else statement in SQL Server -
DECLARE #val INT;
SET #val = 15;
IF #val < 25
PRINT 'Hi Ravi Anand.';
ELSE
BEGIN
IF #val < 50
PRINT 'what''s up?';
ELSE
PRINT 'Bye Ravi Anand.';
END;
GO
Use a CASE statement:
SELECT CASE
WHEN (Obsolete = 'N' OR InStock = 'Y')
THEN 'Y'
ELSE 'N'
END as Available
etc...
A new feature, IIF (that we can simply use), was added in SQL Server 2012:
SELECT IIF ( (Obsolete = 'N' OR InStock = 'Y'), 1, 0) AS Saleable, * FROM Product
Use pure bit logic:
DECLARE #Product TABLE (
id INT PRIMARY KEY IDENTITY NOT NULL
,Obsolote CHAR(1)
,Instock CHAR(1)
)
INSERT INTO #Product ([Obsolote], [Instock])
VALUES ('N', 'N'), ('N', 'Y'), ('Y', 'Y'), ('Y', 'N')
;
WITH cte
AS
(
SELECT
'CheckIfInstock' = CAST(ISNULL(NULLIF(ISNULL(NULLIF(p.[Instock], 'Y'), 1), 'N'), 0) AS BIT)
,'CheckIfObsolote' = CAST(ISNULL(NULLIF(ISNULL(NULLIF(p.[Obsolote], 'N'), 0), 'Y'), 1) AS BIT)
,*
FROM
#Product AS p
)
SELECT
'Salable' = c.[CheckIfInstock] & ~c.[CheckIfObsolote]
,*
FROM
[cte] c
See working demo: if then without case in SQL Server.
For start, you need to work out the value of true and false for selected conditions. Here comes two NULLIF:
for true: ISNULL(NULLIF(p.[Instock], 'Y'), 1)
for false: ISNULL(NULLIF(p.[Instock], 'N'), 0)
combined together gives 1 or 0. Next use bitwise operators.
It's the most WYSIWYG method.
SELECT 1 AS Saleable, *
FROM #Product
WHERE ( Obsolete = 'N' OR InStock = 'Y' )
UNION
SELECT 0 AS Saleable, *
FROM #Product
WHERE NOT ( Obsolete = 'N' OR InStock = 'Y' )
SELECT CASE WHEN profile.nrefillno = 0 THEN 'N' ELSE 'R'END as newref
From profile
case statement some what similar to if in SQL server
SELECT CASE
WHEN Obsolete = 'N' or InStock = 'Y'
THEN 1
ELSE 0
END as Saleable, *
FROM Product
This isn't an answer, just an example of a CASE statement in use where I work. It has a nested CASE statement. Now you know why my eyes are crossed.
CASE orweb2.dbo.Inventory.RegulatingAgencyName
WHEN 'Region 1'
THEN orweb2.dbo.CountyStateAgContactInfo.ContactState
WHEN 'Region 2'
THEN orweb2.dbo.CountyStateAgContactInfo.ContactState
WHEN 'Region 3'
THEN orweb2.dbo.CountyStateAgContactInfo.ContactState
WHEN 'DEPT OF AGRICULTURE'
THEN orweb2.dbo.CountyStateAgContactInfo.ContactAg
ELSE (
CASE orweb2.dbo.CountyStateAgContactInfo.IsContract
WHEN 1
THEN orweb2.dbo.CountyStateAgContactInfo.ContactCounty
ELSE orweb2.dbo.CountyStateAgContactInfo.ContactState
END
)
END AS [County Contact Name]
If you're inserting results into a table for the first time, rather than transferring results from one table to another, this works in Oracle 11.2g:
INSERT INTO customers (last_name, first_name, city)
SELECT 'Doe', 'John', 'Chicago' FROM dual
WHERE NOT EXISTS
(SELECT '1' from customers
where last_name = 'Doe'
and first_name = 'John'
and city = 'Chicago');
As an alternative solution to the CASE statement, a table-driven approach can be used:
DECLARE #Product TABLE (ID INT, Obsolete VARCHAR(10), InStock VARCHAR(10))
INSERT INTO #Product VALUES
(1,'N','Y'),
(2,'A','B'),
(3,'N','B'),
(4,'A','Y')
SELECT P.* , ISNULL(Stmt.Saleable,0) Saleable
FROM
#Product P
LEFT JOIN
( VALUES
( 'N', 'Y', 1 )
) Stmt (Obsolete, InStock, Saleable)
ON P.InStock = Stmt.InStock OR P.Obsolete = Stmt.Obsolete
Result:
ID Obsolete InStock Saleable
----------- ---------- ---------- -----------
1 N Y 1
2 A B 0
3 N B 1
4 A Y 1
SELECT CASE WHEN Obsolete = 'N' or InStock = 'Y' THEN 1 ELSE 0
END AS Saleable, *
FROM Product
You can have two choices for this to actually implement:
Using IIF, which got introduced from SQL Server 2012:
SELECT IIF ( (Obsolete = 'N' OR InStock = 'Y'), 1, 0) AS Saleable, * FROM Product
Using Select Case:
SELECT CASE
WHEN Obsolete = 'N' or InStock = 'Y'
THEN 1
ELSE 0
END as Saleable, *
FROM Product
Using SQL CASE is just like normal If / Else statements.
In the below query, if obsolete value = 'N' or if InStock value = 'Y' then the output will be 1. Otherwise the output will be 0.
Then we put that 0 or 1 value under the Salable Column.
SELECT
CASE
WHEN obsolete = 'N' OR InStock = 'Y'
THEN 1
ELSE 0
END AS Salable
, *
FROM PRODUCT
Question:
SELECT IF(Obsolete = 'N' OR InStock = 'Y' ? 1 : 0) AS Saleable, * FROM Product
ANSI:
Select
case when p.Obsolete = 'N'
or p.InStock = 'Y' then 1 else 0 end as Saleable,
p.*
FROM
Product p;
Using aliases -- p in this case -- will help prevent issues.
SELECT
if((obsolete = 'N' OR instock = 'Y'), 1, 0) AS saleable, *
FROM
product;
For those who uses SQL Server 2012, IIF is a feature that has been added and works as an alternative to Case statements.
SELECT IIF(Obsolete = 'N' OR InStock = 'Y', 1, 0) AS Salable, *
FROM Product
It will be something like that:
SELECT OrderID, Quantity,
CASE
WHEN Quantity > 30 THEN "The quantity is greater than 30"
WHEN Quantity = 30 THEN "The quantity is 30"
ELSE "The quantity is under 30"
END AS QuantityText
FROM OrderDetails;
I like the use of the CASE statements, but the question asked for an IF statement in the SQL Select. What I've used in the past has been:
SELECT
if(GENDER = "M","Male","Female") as Gender
FROM ...
It's like the Excel or sheets IF statements where there is a conditional followed by the true condition and then the false condition:
if(condition, true, false)
Furthermore, you can nest the if statements (but then use should use a CASE :-)
(Note: this works in MySQL Workbench, but it may not work on other platforms)
For the sake of completeness, I would add that SQL uses three-valued logic. The expression:
obsolete = 'N' OR instock = 'Y'
Could produce three distinct results:
| obsolete | instock | saleable |
|----------|---------|----------|
| Y | Y | true |
| Y | N | false |
| Y | null | null |
| N | Y | true |
| N | N | true |
| N | null | true |
| null | Y | true |
| null | N | null |
| null | null | null |
So for example if a product is obsolete but you dont know if product is instock then you dont know if product is saleable. You can write this three-valued logic as follows:
SELECT CASE
WHEN obsolete = 'N' OR instock = 'Y' THEN 'true'
WHEN NOT (obsolete = 'N' OR instock = 'Y') THEN 'false'
ELSE NULL
END AS saleable
Once you figure out how it works, you can convert three results to two results by deciding the behavior of null. E.g. this would treat null as not saleable:
SELECT CASE
WHEN obsolete = 'N' OR instock = 'Y' THEN 'true'
ELSE 'false' -- either false or null
END AS saleable
There are multiple conditions.
SELECT
(CASE
WHEN RIGHT((LEFT(POSID,5)),4) LIKE '1001' THEN 'DM'
WHEN RIGHT((LEFT(POSID,5)),4) LIKE '1002' THEN 'GS'
WHEN RIGHT((LEFT(POSID,5)),4) LIKE '1003' THEN 'MB'
WHEN RIGHT((LEFT(POSID,5)),4) LIKE '1004' THEN 'MP'
WHEN RIGHT((LEFT(POSID,5)),4) LIKE '1005' THEN 'PL'
WHEN RIGHT((LEFT(POSID,5)),4) LIKE '1008' THEN 'DM-27'
WHEN RIGHT((LEFT(POSID,5)),4) LIKE '1011' THEN 'PB'
WHEN RIGHT((LEFT(POSID,5)),4) LIKE '1012' THEN 'UT-2'
WHEN RIGHT((LEFT(POSID,5)),4) LIKE '1013' THEN 'JGC'
WHEN RIGHT((LEFT(POSID,5)),4) LIKE '1014' THEN 'SB'
WHEN RIGHT((LEFT(POSID,5)),4) LIKE '1015' THEN 'IR'
WHEN RIGHT((LEFT(POSID,5)),4) LIKE '1016' THEN 'UT-3'
WHEN RIGHT((LEFT(POSID,5)),4) LIKE '1017' THEN 'UT-4'
WHEN RIGHT((LEFT(POSID,5)),4) LIKE '1019' THEN 'KR'
WHEN RIGHT((LEFT(POSID,5)),4) LIKE '1020' THEN 'SYB-SB'
WHEN RIGHT((LEFT(POSID,5)),4) LIKE '1021' THEN 'GR'
WHEN RIGHT((LEFT(POSID,5)),4) LIKE '1022' THEN 'SYB-KP'
WHEN RIGHT((LEFT(POSID,5)),4) LIKE '1026' THEN 'BNS'
ELSE ''
END) AS OUTLET
FROM matrixcrm.Transact