Converting c++ switch with if statement to Sql - c++

I wrote a bunch of code in c++ to check for a multiple conditions and also I make use of case. Now am struggling to convert it sql case. Below is the c++ code
Switch(TypeEmp){
case 0:
if(Age < 65){
if((income >=0) || (income <=1880000)){
amnt= income * 52 ;
}else if(other condition){
calculate it amnt;
}
}
break;
}

Somthing like this
select ...
case
when (Age < 65) then
case
when (Income >= 0) or (Income <= 1880000) then
income * 52
when (other condition) then
--TODO: compute other condition amount - "calculate it amnt"
else
--TODO: compute amount here
end
else
--TODO: return right value here
end as amnt
...
from MyTable(s)

It'd be something like
SELECT CASE
WHEN AGE < 65 THEN
CASE
WHEN INCOME >= 0 OR INCOME <= 1880000 THEN
INCOME * 52
ELSE
CALCULATE_IT_AMNT
END
ELSE
NULL
END AS SOME_VALUE
FROM SOME_TABLE
This presumes that SOME_TABLE contains the AGE and INCOME columns used in the calculation.

Related

Evaluating boolean with two char variables in c++

Apologies, a bit of a beginner here:
I'm working on a practice program to determine cost of a long distance call based on hour of the day and day of the week...and I've gotten to my do-while loop and am attempting to use nested branches to split up weekdays with the weekend.
However, when I compile and run, both the if and else if nested statements are skipped no matter if I put in the Chars corresponding to the booleans I'm attempting to evaluate. I'm struggling to understand what I'm missing here. The instructions clearly state that the days of the week should be stored in two char variables: Mo Tu We Th Fr Sa Su.
do
{
//have user input day of week of call
printf("\nOn what day was the call made? (Mo, Tu, We, Th, Fr, Sa, or Su) ");
scanf("%c%c", &day1, &day2);
//branch for weekday vs weekend vs invalid input
if (((day1 == 'M') && (day2 == 'o')) || ((day1 == 'T') && (day2 == 'u')) || ((day1 == 'W') && (day2 == 'e')) || ((day1 == 'T') && (day2 == 'h')) || ((day1 == 'F') && (day2 == 'r')))
{
//determine if phone call was made at hi or low rate times
printf("At what time was your call made? (HH MM - with 08 00 representing 8:00 AM and 18 30 representing 6:30 PM) ");
scanf("%f %f", &call_time_hour, &call_time_minute);
call_time_hour = call_time_hour + (call_time_minute / 60);
printf("%f", call_time_hour);
}
else if (((day1 == 'S') && (day2 == 'a')) || ((day1 == 'S') && (day2 == 'u')))
{
printf("What was the duration of your call? ");
scanf("%d", &call_duration);
//calculate total cost of call
cost_of_call = call_duration * 0.15;
printf("%s %.2lf", "The cost of this call was $", cost_of_call);
}
calls_made--;
printf("%d", calls_made);
}while (calls_made > 0);
So, for example, when I compile and run the program and enter "Sa" as the day that the call was made, it then moved directly to the 'calls_made--' step.
The problem is because previous scanf. Debug and look what characters are really scanned. I'm sure that day1 would be '\n'.
In this case clear the input stream before scanning the day of week:
while (getchar() != '\n');

PSQL average with IF/ELSE

I have a psql table with columns including: year, value, ... and so on.
I want to do something like this:
select
CASE WHEN avg(value) >=0 then avg(value)
ELSE -999
END
from my_table
where year >= 2000 and year < 2005 and value >= 0
So I want my average to ignore any years that have negative value, but for cases where all years have negative value, I want to return -999.
This query runs but doesn't return -999 in the case where all values are negative.
If I've understood you correctly you're looking for something like:
select
coalesce(avg(value) filter (when value >= 0), -999)
from my_table
where year >= 2000 and year < 2005;
which returns -999 if all values are negative or there are zero rows that match the WHERE clause. avg returns null if it doesn't get any input rows.
The filter syntax works only on newer PostgreSQL versions. For older ones you must use avg(case when value >= 0 then value end).
you have given in the where clause value>=0 This will only compute the average of non negative values, hence you will never get the average of negative values
where year >= 2000 and year < 2005 and value >= 0
Guess what you are trying to do is this
select
CASE WHEN value >=0 then
(select avg(value) from t_table where value>=0)
ELSE -999
END
from table
where year >= 2000 and year < 2005;

C++ , changing an if/else if into a switch statement

C++ question- "Write a program that will calculate total savings by a student with his/her parents’ contribution. The student’s parents have agreed to add to the student’s savings based the percentage the student saved using the schedule given below" This is the if/else if I used to find out the parents contribution. I now have to make this program again except with a switch statement. I don't know exactly how to do that. The user inputs total earnings, and amount he decided to put away. (My course just started so I have to use very simple processes to do this thank you) Here's the first version:
percent_saved = money_saved / money_earned; // calculates the percent of how much was saved
if (percent_saved <.05) // this if/else if statement assigns the parents percentage of contribution to their students saving
{
parents = .01;
}
else if (percent_saved >= .05 && percent_saved < .1)
{
parents = .025;
}
else if (percent_saved >= .1 && percent_saved < .15)
{
parents = .08;
}
else if (percent_saved >= .15 && percent_saved < .25)
{
parents = .125;
}
else if (percent_saved >= .25 && percent_saved < .35)
{
parents = .15;
}
else
{
parents = .2;
}
parentsmoney = parents*money_earned; // using the correct percentage, this creates the amount of money parents will contribute
total_savings = parentsmoney + money_saved; // this adds together the parent's contribution and the student's savings
This can't (shouldn't) be done in this case: switch is only useful for discrete integer values. It is not useful for non-trivial ranges and cannot be used directly with floats.
Anyway, about half the conditionals can be removed from the if-expressions if the ordering reversed such that the tests are inchworm'ed through..
if (percent_saved >= .35) {
parents = .2;
} else if (percent_saved >= .25) {
parents = .15;
} // etc.
Now, if the requirement is to "use a switch statement" (silly homework problems), then consider first normalizing the floating value into "buckets" such that 0.05 => 1, 0.1 => 2, 0.15 => 3, etc. The resulting integer can then be checked in a relevant case (with some cases being fall-throughs), as shown in the linked question..
int bucket = rint(percent_saved / 0.05);

Date Validation and Conversion in C++

I have to write 2 functions. One that takes in a date as a string and checks if its in mm/dd/yy format; if its not in the correct format, it should be edited to make it so. The other function should convert the validated date to the format "Month dd, 20yy".
I'm pretty sure I can take care of the second function, but I am having trouble with the first one. I just have no idea how to check if its in that format... any ideas?
I thought that this would work, but it doesn't seem to...
Updated code:
bool dateValidation(string shipDate)
{
string temp;
if(shipDate.length() == 8 )
{
if(shipDate[2] == '/' && shipDate[5] =='/')
{
int tempDay, tempMonth, tempYear;
//Gather month
temp = shipDate[0];
temp += shipDate[1];
//convert string to int
tempMonth = temp.atoi;
temp = "";
//Gather day
temp = shipDate[3];
temp += shipDate[4];
//convert string to int
tempDay = temp.atoi;
temp = "";
//Gather year
temp = shipDate[6];
temp += shipDate[7];
//convert string to int
tempYear = temp.atoi;
temp = "";
if(tempMonth > 0 && tempMonth <= 12)
{
if(tempMonth == 9 ||
tempMonth == 4 ||
tempMonth == 6 ||
tempMonth == 11 ||)
{
if(tempDay > 0 && tempDay <= 30)
{
if 30 days
}
}
else if(tempMonth == 2)
{
if(tempDay > 0 && tempDay <= 28)
{
if 28 days
}
}
else
{
if(tempDay > 0 && tempDay <= 31)
{
if 31 days
}
}
}
}
}
}
There are 4 things you want to check:
Is there 8 characters ? If not, then don't even bother checking anything else. It's not in the proper format.
Are the third and fifth characters '/'. If not, then you still don't have the proper format.
Check each pair for its valid values. A month has days between 1 and
31 at most, there are no more than 12 months and months range from 01
to 12. A year can be any combination of any 2 digits.
This should take care of the format, but if you want to make sure that the date is valid:
Check for valid number of days in each month (january 31, february
28-29...) and indeed check for those leap years.
This looks a lot like a project I am about to grade.... You should verify that it is Gregorian Calendar compliant if it is the project I am about to grade. 1/1/2012 is definitely valid though so what you may want to do and what I would hope you consider is creating a switch statement that examines for formats like 1/12/2012 and 10/2/2012 because these are valid. Then parse out the month day and year from these. Then verify that they are within the limit of the Gregorian calendar. If it is for a class which I would guess that it is, you should consider writing the verification as a separate function from the parsing function.
So first ask whether the date is too long if not, is it too short, if not which version is it, then pass the d m y to the verification function. This kind of modularity will simplify your code and reduce instructions.
something like
bool dateValidation(string shipDate)
{
string temp;
switch(shipDate.length())
{
case(10):
// do what your doing
verify(m,d,y);
break;
case(8):
//dealing with single digits
// verify 1 and 3 are '/' and the rest are numbers
verifiy(m,d,y);
break;
case(9):
//a little more heavy lifting here
// but its good thinking for a new programmer
verifiy(m,d,y);
break;
default:
//fail message
break;
}

Multiple if statements comparing text and integers

I am trying to make multiple if statements with multiple conditions. If I run the code it works fine but it never changes the output. I always get the second statement >= 29. Here's my code.
if (label.text <= #"30")
{label.text = #"Text";}
else if (label.text >= #"29")
{label.text = #"Text";}
else if (label.text >= #"19")
{label.text = #"Text";}
else if (label.text >= #"10")
{label.text = #"Text";}
else if (label.text = #"00")
{label.text = #"Text";}
ok I have changed my code but i still doesn't work any suggestions
label.text = temporaryValue;
if ([label.text floatValue] <= 30)
{label.text = #"text1";}
else if ([label.text floatValue] >= 29)
{label.text = #"text2";}
else if ([label.text floatValue] >= 19)
{label.text = #"text3";}
else if ([label.text floatValue] >= 10)
{label.text = #"text4";}
else if ([label.text floatValue] == 0)
{label.text = #"text5";}
You can't compare the numerical values of a string like this; this operation performs pointer comparison, i. e. it compares the (rather random) addresses of the string instances you pass in. Use something like this:
if ([label.text floatValue] >= 30.0) {
}
etc.
Using >= or <= with NSString* would compare the addresses, not the content of those strings. If you want to compare like this, you should parse your string into an int and compare it using common integer comparison:
int val = [label.text intValue];
if (val > 30) {
...
}
else ... // more of your ifs
Once you fix your syntax (as suggested in other answers here) you will still have a problem, as once you are dealing with numeric comparisons your logic flow seems flawed. Consider this
if ([label.text floatValue] <= 30.0)
{label.text = #"Text";}
else if ([label.text floatValue] >= 29.0)
{label.text = #"Text";}
if your test value IS greater than 30, you move to the next else if
else if ([label.text floatValue] >= 29.0)
clearly this IS bigger than 29 since it failed to be less than or equal to 30. Therefore all your other conditonals are never reached as assuming your first conditional is false, the second MUST be true.