How to do a complicated case statement
In my windows form program a user can create an invoice for customers. In order to load the products to create the invoice, I need to make an sql stored procedure that takes the products from the products table. The problem is that there is something called
pricebooks in which a specific customer or group of customers can get a special price for a specific item and then when loading the products for the invoice if this customer has a special price it should put in the special price, if this customer belongs to
a group that has a special price it should show that price else it should show the regular price for that item from the products table. How would I do that? I tried something and for any row that it had a customer and item matching in pricebooks as well it
put that product down twice.
SELECT ITEM, DESCRIPTION, ONHAND, CASE WHEN P.CUSTOMER = @CUSTOMER THEN P.PRICE WHEN C.PRICEGROUP = P.PRICEGROUP AND P.CUSTOMER = @CUSTOMER THEN P.PRICE ELSE I.PRICE END AS PRICE, COST, RETAIL FROM INVENTORY I LEFT JOIN PRICEBOOKS P ON I.ITEM = P.ITEM LEFT
JOIN CUSTOMER C ON C.PRICEGROUP = P.PRICEGGROUP
The pricebook table can have either a customer with the item that has a special price or a pricegroup with an item that has a special price and in the customer table some customers have that pricegroup. (can be many pricegroups).
Debra has a question
Thank you so much for your help. I tweaked up the procedure a little and now it works for my code.
CREATE PROCEDURE PriceBookByCustomer (@CustomerId int)
--declare @CustomerId int
--set @CustomerId = 659
--look up customer's group from customers table
Declare @GroupId int
SELECT @GroupId = PRICEGROUP FROM CUSTOMER WHERE ID = @CustomerId
--get inventory, outer join to special customer pricing, outer join to special group pricing
SELECT I.ITEM, I.DESCRIPTION, I.ONHAND, COALESCE(CP.PRICE, GP.PRICE, I.PRICE) AS PRICE
, COST, RETAIL
FROM INV I
LEFT JOIN PRICEBOOKS CP
ON I.ITEM = CP.ITEM AND CP.Customer = @CustomerId
LEFT JOIN PRICEBOOKS GP
ON I.ITEM = GP.ITEM AND GP.GroupId = @GroupId
ORDER BY I.ITEM
Debra has a question
Similar Messages
-
How do I write a case statement If I want a case for x < 1.5; a case for 1.5 <= x <= 3.7; case for 3.7 < x < 7.2.....etc. My input is a floating number.
Thank you.
Solved!
Go to Solution.smercurio_fc wrote:
Nice method with the Threshold function. I was not aware of the limitation with -Inf. Odd.
Actually, my code operates correctly as long as the first element is smaller than all other elements in the array. We don't need any special handling.
Maybe NaN is not a bug if the array starts with -Inf, because the interpolated index for any number between the second element and -inf will be infinitely close to 1, thus a result of zero can never be obtained (try a first element of -1e50 and you'll always get 1 unless you go to very huge negative numbers).
The way threshold array is defined, the behavior should be obvious, the problem is assigning a fractional index.
It is unexpected that an input equal to the second element also results in NaN. That might be a bug. (see image).
I probably won't post an idea, maybe a bug report after some more thinking...
LabVIEW Champion . Do more with less code and in less time .
Attachments:
IdeaThresholdArray.png 19 KB -
How do I use the CASE statement in the where clause?
Hello Everyone,
I have 2 queries that do what I need to do but I am trying to learn how to use the CASE statement.
I have tried to combine these 2 into one query using a case statement but don't get the results I need.
Could use some help on how to use the case syntax to get the results needed.
thanks a lot
select segment_name,
product_type,
count (distinct account_id)
FROM NL_ACCT
where
ind = 'N'
and
EM_ind = 'N'
and product_type in ('TAX','PAY')
and acct_open_dt between (cast('2006-01-17' as date)) and (cast('2006-01-17' as date) + 60)
GROUP BY 1,2
order by product_type
select segment_name,
product_type,
count (distinct account_id)
FROM NL_ACCT
where
ind = 'N'
and
EM_ind = 'N'
and product_type not in ('TAX','PAY')
and acct_open_dt between (cast('2006-01-17' as date)) and (cast('2006-01-17' as date) + 30)
group by 1,2
order by product_typeSomething like:
SELECT segment_name, product_type,
SUM(CASE WHEN account_id IN ('TAX','PAY') and
acct_open_dt BETWEEN TO_DATE('2006-01-17', 'yyyy-mm-dd') and
TO_DATE('2006-01-17', 'yyyy-mm-dd') + 60 THEN 1
ELSE 0 END) tax_pay,
SUM(CASE WHEN account_id NOT IN ('TAX','PAY') and
acct_open_dt BETWEEN TO_DATE('2006-01-17', 'yyyy-mm-dd') and
TO_DATE('2006-01-17', 'yyyy-mm-dd') + 30 THEN 1
ELSE 0 END) not_tax_pay
FROM NL_ACCT
WHERE ind = 'N' and
em_ind = 'N' and
acct_open_dt BETWEEN TO_DATE('2006-01-17', 'yyyy-mm-dd') and
TO_DATE('2006-01-17', 'yyyy-mm-dd') + 60
GROUP BY segment_name, product_type
ORDER BY product_typeNote: You cannor GROUP BY 1,2, you need to explicitly name the columns to group by.
HTH
John -
How to take care of case statements while migration
Hello Sir,
using migration workbench tool for converting SQL server database to Oracle Databse.Getting error message in converting below SP with Case Statement.
Please help me in solving this problem
****** Object: Stored Procedure dbo.SP_Sec_GetScreenFieldAccessLevel
Procedure Name : SP_Sec_GetScrnFldAccessLevel
Notes :
This procedure selects data from E_E_C_field_Access_level table
CREATE PROCEDURE SP_Sec_GetScrnFldAccessLevel
AS
Select Screen_ID + '-' + FieldDescription as ScreenFieldName
,Level=
CASE
WHEN Len(IsNull(E_E_C_field_Access_level.ein_code,''))= 1 THEN campus_name
WHEN Len(E_E_C_field_Access_level.ein_code)> 1 THEN ein_name
END,
ein_name,campus_name,Urole,
IsLocked=case IsLocked
when 1 then 'Yes'
when 0 then 'No'
End
from E_E_C_field_Access_level,Field_Name_Field_Description,User_Roles_Master,EIN,Campus
where
E_E_C_field_Access_level.Screen_Field_ID*=Field_Name_Field_Description.ID
and E_E_C_field_Access_level.User_role_Id *=User_Roles_Master.Role_Id
and E_E_C_field_Access_level.ein_code *= EIN.ein_code
and E_E_C_field_Access_level.campus_code *= Campus.campus_code
and E_E_C_field_Access_level.del_flag=0
order by E_E_C_field_Access_level.date_created desc
IF @@ERROR <> 0
RETURN @@ERROR
ELSE
RETURN 0If not using the new SQL DEveloper Migration Workbench, then u should be. I think this new version takes care of case statements.
-
How to manipulate arrays using case statements and boolean conditions?
In the vi that is attached I am trying to compare two values in two different arrays and delete the value that is equal to zero. The values of each array are rounded to the closest integer. Then I attempted to apply the ">0" boolean as the condition for my case statement, but I am getting an error. Any tips on manipulating arrays with case statements?
Attachments:
Patient Movement Monitoring.vi 141 KBThank you!!! that was a huge help. I don't think I need the case structures at all. The next part of the code compares the 4 values in the array.
If columns 0 and 1 are both positive -> output 1
If column 0 is negative and 1 is positive -> output 2
If columns 0 and 1 are both negative -> output 3
If column 0 is positive and 1 is negative -> output 4
(0 is x-axis value, 1 is y-axis value.....outputs are assigning quadrants to the combination)
Only one of the "AND" booleans will return true for each index. Is there a way to initialize another array of outputs 1-4 depending on which AND returns true?
Attachments:
Patient Movement Monitoring.vi 144 KB -
How to use REGEXP for case statement
Hello everyone, I'm very new here and am struggling with a using REGEXP in a case statement, OK I am using the REGEXP to find all strings that match a specific format for a particular brand of product, for example serial numbers, and I need to be able to say something like [case when(xx.brandid) = '123' then if xx.serialnumber REGEXP_LIKE(xx.serialnumber,'[A-za-z][A-za-z][A-za-z]\d{5,}[A-za-z]$') then 'TRUE' else 'FALSE' end "TRUE/FALSE".]
Help would be greatly appreciated with this as I feel like I'm going backwards trying to figure this out
Thanks in advance for any assistance.Like this?
case
when xx.brandid = '123' and
regexp_like(xx.serialnumber,'[A-za-z][A-za-z][A-za-z]\d{5,}[A-za-z]$') then
'TRUE'
else
'FALSE'
end -
How to convert the compund case statement into decode statement
(CASE
WHEN FRCST = 0 AND SALE = 0 THEN 'No transaction '
WHEN FRCST = 0 AND SALE <>0 THEN 'Sale ag. Nil Forecast : '||SALE||' Kgs'
WHEN FRCST<> 0 AND SALE = 0 THEN 'No Sale ag. Forecast : '||FRCST||' Kgs'
WHEN FRCST<>0 AND SALE<>0 AND DIFF=0 THEN 'No Variance'
ELSE TO_CHAR(ROUND((DIFF/FRCST),2))||'%'
END)VARIANCE
How to convert this tatement to decode statement ?
YogeshDecode(FRCST,0,DECODE(SALE,0,'nO TRANSACTION','SALE AGAINST NIL FORECAST'),DECODE(SALE,0,'NO SALE AGAINST FORECAST',
DECODE(|SALE-FORECAST|,0,'NO VARIANCE',TO_CHAR(ROUND((DIFF/FRCST),2))||'%')))As per me whole case can be replaced by above decode -
How should I pass complicated sql statements to a function ?
Hello
Some built-in functions, such as dbms_advisor.quicktune accepts sql statements as in parameters. Those parameters are treated as varchar2, but if the sql statement is complicated and contain " ' " characters then its hard to pass those params, Sometimes they arent parsed correctly.
How should I pass a complicated statement (with subqueries, strings and so) to a function ?
Thanks
Guyuser11973359 wrote:
Hello
Some built-in functions, such as dbms_advisor.quicktune accepts sql statements as in parameters. Those parameters are treated as varchar2, but if the sql statement is complicated and contain " ' " characters then its hard to pass those params, Sometimes they arent parsed correctly.
How should I pass a complicated statement (with subqueries, strings and so) to a function ?
Thanks
GuyWhats your db verzion. To over come the single quotes issue in string you can use q'[]' representation of string.
select q'[Karthick's]' from dual -
How to write the following CASE statement
I need to calculate Retainer amount. The derivation of it is as follows:
"A fixed value of 10000 per month for employees who have served for less than 2 years and 15000 for more than 2 years. This increment will be affected in two cycles a year, in the January or July."
The years of service can be calculated using date_of_joining.Use this logic
SELECT DECODE(SIGN(SYSDATE - ADD_MONTHS(HIREDATE,24)),-1,10000,1,15000) from <table_name>Is this you need
In every Jan/July month employee get a Sal+Fixed allownce (10000 if less than 2 years in company/15000 if more than 2 years). In other month they get just the salary
SELECT CASE WHEN TO_CHAR(SYSDATE,'MM') IN ('01','07') THEN
CASE WHEN SYSDATE- ADD_MONTHS(HIREDATE,24)> 0 THEN
SAL+15000
ELSE
SAL+10000
END
ELSE
SAL
END SAL
FROM EMP
/Edited by: Lokanath Giri on १७ सितंबर, २०१० ४:५६ अपराह्न -
How to validate date using case statement.
I have date like 022212. I split month,date,year using STUFF Function. Now, i have to validate month in range 01-12 and date in range 01-31. Can some one help me with the query.
Thanks, Shyam Reddy.That is not date; it is apparently a string (we have no DDL because you are so rude). Any competent SQL programmer will use DATE. You want help with a query, but there is no query.
CAST ('20' + SUBSTRING (crap_string_date, 5,2)+'-' + SUBSTRING (crap_string_date, 1,2) + '-' + SUBSTRING (crap_string_date, 3,2) AS DATE) AS redddy_screwed_up_date
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL -
CASE statement in Calculated column
Hi Frzz,
I have below requirement in Calculated column with CASE statement. Could some one help me how to achieve this with case statement.
String = 0Hello
01Hello
012Hello
0123Hello
If 1st Character of the string is '0' then - 0Hello
1st 2 characters of the String is '01' - 22Hello
1st 3 characters of the String is '01' - 333Hello
1st 4 characters of the String is '01' - 4444Hello
Thank you.
Best Regards,
Krishna.Hi Krishna ,
Using IF and MATCH to do that: ( I took one of the conditions you specified )
IF(match("STRING1",'??0??'),'333Hello',"STRING1")
Output:
Regards,
Krishna Tangudu -
More than one variable at a time in case statement
hi i am using oracle 10g database.
can it be possible ?
in if condition we can have more than one variable in one condition
if a=100 then
b:=200;
c:=300;
end if;
how it will be in case statement ? i have searched lot on internet but didnt get
case
when a=100 then 200, 300 ... ???
thanksHi FRNzzz!! wrote:
hi i am using oracle 10g database.
can it be possible ?
in if condition we can have more than one variable in one condition
if a=100 then
b:=200;
c:=300;
end if; how it will be in case statement ? i have searched lot on internet but didnt get
case
when a=100 then 200, 300 ... ???
thanksnot sure if I got your question correctly, is this what you are looking for?
SQL> ed
Wrote file afiedt.buf
1 declare
2 a number := 100;
3 b number;
4 c number;
5 begin
6 case
7 when a = 100 then
8 b := 200;
9 c := 300;
10 when a = 0 then
11 b := 300;
12 c := 400;
13 else
14 b := 0;
15 c := 0;
16 end case;
17 dbms_output.put_line('a :'||a||' b :'||b||' c :'||c);
18* end;
SQL> /
a :100 b :200 c :300
PL/SQL procedure successfully completed. -
Case statement within where clause
How can i write a case statement within Where clause of SQL statement.
Ex:
If sysdate is less than Dec 31 of 2009 then run the query for 2009 else run the query for 2010.
belwo query is not working. Please let me know how can i write a case statement within where clause.
Select * from table
where
Case
when to_char(sysdate,'yyyymmdd')<=20091231 then tax_year=2009
else tax_year=2010
EndHi,
You can get the results you want like this:
Select *
from table
where tax_year = Case
when to_char(sysdate,'yyyymmdd') <= 20091231
then 2009
else 2010
End
;A CASE expression returns a single value in one of the SQL data types, such as a NUMBER, VARCHAR2 or DATE. There is no boolean type in SQL. -
Please Help!!!
How to write a case statement for the totals column of two different years (2013 and 2014) of the same month so that I can get a +/- column.
January 2014 January
2013 +/-
Region Entry Exit Total Entry Exit Total (Total of Jan2014-Total of Jan2013)
A 2 3
40 5 7 30 40-30= 10What is a table structure? Sorry cannot test it right now..
SELECT <columns>,(SELECT Total FROM tbl WHERE Y=2014)-(SELECT Total FROM tbl WHERE Y=2013)
FROM tbl
Best Regards,Uri Dimant SQL Server MVP,
http://sqlblog.com/blogs/uri_dimant/
MS SQL optimization: MS SQL Development and Optimization
MS SQL Consulting:
Large scale of database and data cleansing
Remote DBA Services:
Improves MS SQL Database Performance
SQL Server Integration Services:
Business Intelligence -
How to use a CTE in a CASE statement?
Hi everyone,
I'm trying to use a CTE in a CASE statement and getting error. In fact, I'm not sure how to use a CTE in this case and this is the first time I'm using a CTE. I managed to build a CTE successfully but, failed to incorporate it in the CASE statement.
SELECT wbs,
MIN(srt),
MAX(srt)
CASE ust
WHEN
WITH CTE AS
SELECT p_id + p_name + ps_name AS colg, p_id
FROM pd_info
WHERE s_desc = 'warehouse'
OR p_desc = 'Originated from warehouse'
OR p_desc = 'Originated from a partner store'
SELECT colg FROM CTE
WHERE cte.colg IN (SELECT p_id + p_name + ps_name AS c
omb from pd_info)
OR cte.p_id = 'xxxxxxxx' THEN 'invalid'
ELSE 'valid'
END,
p_name,
sub_name,
ps_name,
FROM pd_info;
Could experts here please help me?
Thank you,
Bangaaram
Known is a DROP, Unknown is an OCEAN.With the help from some experts, I've figured out that CTE doesn't work in this case. Here are the queries that I'm using for the above. Either of them is working good so far.
SELECT Wbs
, MIN ( Srt )
, MAX ( Srt )
, CASE
WHEN S_Desc = 'warehouse'
OR P_Desc = 'Originated from warehouse'
OR P_Desc = 'Originated from a partner store'
OR P_Id = 'xxxxxxxx'
THEN 'invalid'
ELSE 'valid'
END AS Ust
, P_Name
, Sub_Name
, Ps_Name
FROM Pd_Info
GROUP BY Wbs
, CASE
WHEN S_Desc = 'warehouse'
OR P_Desc = 'Originated from warehouse'
OR P_Desc = 'Originated from a partner store'
OR P_Id = 'xxxxxxxx'
THEN 'invalid'
ELSE 'valid'
END
, P_Name
, Sub_Name
, Ps_Name;
SELECT wbs,
MIN(srt),
MAX(srt)
CASE
WHEN cte.p_id = 'xxxxxxxx'
or exists
(select *
from pd_info p2
WHERE (s_desc = 'warehouse'
OR p_desc = 'Originated from warehouse'
OR p_desc = 'Originated from a partner store' )
and p2.p_id = p1.p_id and p2.p_name = p1.p_name and p2.ps_name = p1.ps_name
THEN 'invalid'
ELSE 'valid'
END ust,
p_name,
sub_name,
ps_name,
FROM pd_info p1;
Thank you,
Bangaaram
Known is a DROP, Unknown is an OCEAN.
Maybe you are looking for
-
Define Multiple Taxes with different Accounts
Dear Members I have defined tax in Oracle R12 . and defined multiple rates. these all tax deducted in a single Tax account. but my requirement is, there should be multiple taxes with different acccounts. when I define multiple taxes the system gives
-
Fullscreen on one monitor, while working on the other?
Mac Pro running Maverick OSX. When I go into fullscreen with youtube on one monitor, and click anywhere on my secondary monitor: Youtube exits fullscreen. I've tested this with another machine running OSX Mountain Lion. With Mountain Lion I can have
-
Error generating XML in Apex 4.1.1
Hi, please, I need your help. I have an XML develped in APEX with this process: declare begin select xmlElement( "iva", xmlElement("numeroRuc",J.RUC), xmlElement("mes", J.MES), xmlElement( "compras", ( select xmlAgg( xmlElement( "detalleCompra", xmlE
-
Refund Policy on a new non-working T430
Anyone knows what is Lenovo policy on returning the 'lemon' new laptop and receiving refund. I am totally frustrated with the T430 that I received yesterday. I want nothing to do anymore with this laptop and Lenovo. I just want my money back. Below i
-
I researched this topic on the forum but most of the posts are from last June. Much has been updated with the Pre since then. I use Outlook 2003 and have Road Runner access for my personal email. I would like to know if there is a way to sync my pe