Simple If Else statement in sql - mysql

I'm trying to get only the rows that are in USD and EUR from a table with more currencies.
I thought the code should be something like:
SELECT IF(CONTRACTS_IN_DIFFERENT_CURRENCIES.CURRENCY='USD',1,0) OR IF(CONTRACTS_IN_DIFFERENT_CURRENCIES.CURRENCY='EUR',1,0
FROM CONTRACTS_IN_DIFFERENT_CURRENCIES
But I know this is not how it should be. I would like the table to be something like a column of USD and EUR

It looks as though you're trying to use Excel's IF(condition, true_response, false_response) syntax. The equivalent in T-SQL is the CASE WHEN THEN ELSE END syntax:
SELECT
CASE
WHEN CONTRACTS_IN_DIFFERENT_CURRENCIES.CURRENCY ='USD' THEN 1
WHEN CONTRACTS_IN_DIFFERENT_CURRENCIES.CURRENCY='EUR' THEN 1
ELSE 0
END
FROM
CONTRACTS_IN_DIFFERENT_CURRENCIES
This will work with more complex queries than the example you're giving us. Another way of doing it, if you have a number of possible values for the same field that will return the same response, would be
SELECT
CASE
WHEN CONTRACTS_IN_DIFFERENT_CURRENCIES.CURRENCY IN ('USD','EUR') THEN 1
ELSE 0
END
FROM
CONTRACTS_IN_DIFFERENT_CURRENCIES
However, that is not the right syntax to use to get just the rows with certain currencies; the previous answer with
SELECT *
FROM
CONTRACTS_IN_DIFFERENT_CURRENCIES
WHERE
CONTRACTS_IN_DIFFERENT_CURRENCIES.CURRENCY IN ('USD','EUR')
would work best for that.

The preceding answers are good in my opinion, but let's say you would have alot of currencies, you could do
SELECT * FROM CONTRACTS_IN_DIFFERENT_CURRENCIES WHERE CURRENCY IN ("USD","EUR")

SELECT *
FROM CONTRACTS_IN_DIFFERENT_CURRENCIES WHERE
CONTRACTS_IN_DIFFERENT_CURRENCIES.CURRENCY='USD' OR CONTRACTS_IN_DIFFERENT_CURRENCIES.CURRENCY='EUR'
OR
SELECT *
FROM CONTRACTS_IN_DIFFERENT_CURRENCIES WHERE
`CONTRACTS_IN_DIFFERENT_CURRENCIES`.`CURRENCY`="USD" OR `CONTRACTS_IN_DIFFERENT_CURRENCIES`.`CURRENCY`="EUR"
I have not understand ,1,0) that part. So if you need some more condition use AND, OR and combination of brackets to achieve result.
Just to let you know, if you need disctinc (non repeating values) you can use word DISTINCT and state what fields exactly you need.

You need to use a WHERE clause.
As far as I can tell you're looking for a query along the lines of
SELECT * FROM `CONTRACTS_IN_DIFFERENT_CURRENCIES` WHERE `CURRENCY` = "USD" OR `CURRENCY` = "EUR"

If you want the count of the number of contracts in each of those currencies with each count as a column (which seems to be indicated by one of the comments in your question), then use this…
SELECT SUM(CURRENCY = 'USD') AS usdContracts,
SUM(CURRENCY = 'EUR') AS eurContracts
FROM CONTRACTS_IN_DIFFERENT_CURRENCIES
If you want the count of the number of contracts in each of those currencies with each count as a row with the count in one column and the currency abbreviation in another, then use this…
SELECT COUNT(*) AS numContracts, CURRENCY AS currency
FROM CONTRACTS_IN_DIFFERENT_CURRENCIES
WHERE CURRENCY = 'USD' OR CURRENCY = 'EUR'
GROUP BY CURRENCY;

Related

sql COALESCE result (12300.4567) to 12,300

How to select COALESCE result to format( , 0)
my query is
SELECT (COALESCE((SELECT SUM(`invoices`.`paid_amount`) FROM `invoices`
WHERE DATE(`invoices`.`date`)=CURDATE()),0) +
COALESCE((SELECT SUM(`other_incomes`.`other_income_amount`) FROM `other_incomes`
WHERE DATE(`other_incomes`.`date`)=CURDATE()),0))
AS total
FROM
....
Primarily, COALESCE doesn't change the formatting. It only returns the first non-null value passed to it.
Also, instead of trying to join or do two different queries and adding, and handling all the sums and coalesces separately (not to mention the rounding), I would probably UNION all the relevant results together, then handle the coalesce/sum/round all at the end.
Try this:
SELECT round(sum(coalesce(amt, 0)), 0) as total
FROM (
SELECT paid_amount as amt
FROM invoices i
WHERE date(i.date) = CURDATE()
union all
SELECT other_income_amount
FROM other_incomes o
WHERE date(o.date) = CURDATE()
) z
Here I COALESCE first, to make nulls be 0 instead. I wrap that in a SUM to add up the values, and finally a ROUND to get the format. It was unclear from the question is you wanted to ROUND or FLOOR. If you are looking to get it with that comma, use FORMAT. Here's the mySQL documentation for that. You didn't specify your SQL flavor.
https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_format
Additionally, you should include your sql platform and version, the create statements for your tables, along with some insert statements that will provide sample data, along with the results you are looking for. It will help people answer your question. If you can include a fiddle, like https://dbfiddle.uk/, that would be nice.

MySQL returns all rows when field=0 from SECOND Select query

This case is similar to: S.O Question; mySQL returns all rows when field=0, and the Accepted answer was a very simple trick, to souround the ZERO with single quotes
FROM:
SELECT * FROM table WHERE email=0
TO:
SELECT * FROM table WHERE email='0'
However, my case is slightly different in that my Query is something like:
SELECT * FROM table WHERE email=(
SELECT my_column_value FROM myTable WHERE my_column_value=0 AND user_id =15 LIMIT 1 )
Which in a sense, becomes like simply saying: SELECT * FROM table WHERE email=0, but now with a Second Query.
PLEASE NOTE: It is a MUST that I use the SECOND QUERY.
When I tried: SELECT * FROM table WHERE email='( SELECT my_column_value FROM myTable WHERE my_column_value=0 LIMIT 1 )' (Notice the Single Quotes on the second query)
MySql SCREAMED Errors near '(.
How can this be achieved
Any Suggestion is highly honored
EDIT1: For a visual perspective of the Query
See the STEN_TB here: http://snag.gy/Rq8dq.jpg
Now, the main aim is to get the sten_h where rawscore_h = 0;
The CURRENT QUERY as a whole.
SELECT sten_h
FROM sten_tb
WHERE rawscore_h = (
SELECT `for_print_stens_rowscore`
FROM `for_print_stens_tb`
WHERE `for_print_stens_student_id` =3
AND `for_print_stens_factor_name` = 'Factor H' )
The result of the Second Query can be any number including ZERO.
Any number from >=1 Works and returns a single corresponding value from sten_h. Only =0 does not Work, it returns all rows
That's the issue.
CORRECT ANSWER OR SOLUTION FOR THIS
Just in case someone ends up in this paradox, the Accepted answer has it all.
SEE STEN_TB: http://snag.gy/Rq8dq.jpg
SEE The desired Query result here: http://snag.gy/wa4yA.jpg
I believe your issue is with implicit datatype conversions. You can make those datatype conversions explicit, to gain control.
(The "trick" with wrapping a literal 0 in single quotes, that makes the literal a string literal, rather than a numeric.)
In the more general case, you can use a CAST or CONVERT function to explicitly specify a datatype conversion. You can use an expression in place of a column name, wherever you need to...
For example, to get the value returned by my_column_value to match the datatype of the email column, assuming email is character type, something like:
... email = (SELECT CONVERT(my_column_value,CHAR(255)) FROM myTable WHERE ...
or, to get the a literal integer value to be a string value:
... FROM myTable WHERE my_column_value = CONVERT(0,CHAR(30)) ...
If email and my_column_value are just indicating true or false then they should almost certainly be both BIT NOT NULL or other two-value type that your schema uses for booleans. (Your ORM may use a particular one.) Casting is frequently a hack made necessary by a poor design.
If it should be a particular user then you shouldn't use LIMIT because tables are unordered and that doesn't return a particular user. Explain in your question what your query is supposed to return including exactly what you mean by "15th".
(Having all those similar columns is bad design: rawscore_a, sten_a, rawscore_b, sten_b,... . Use a table with two columns: rawscore, sten.)

Trouble in SQL Summing a Word

I am trying to Sum() the column Status where Status = 'operational'. I am having trouble figuring out how to sum the actual word "operational".
I have tried multiple different variations of the statement below (the one I posted is the most basic form) but I get the error: data type varchar is invalid for sum operator.
Can anybody help?
SELECT SUM(status) As 'TotalOperationalSTIDevices'
FROM netinfo_device_details
WHERE LoopBackAddress LIKE '10.12%' AND Status = 'Operational'
Try
Select COUNT(*) As 'TotalOperationalSTIDevices' from netinfo_device_details where LoopBackAddress Like '10.12%' and Status = 'Operational'
You need to use COUNT:
SELECT COUNT(*) As TotalOperationalSTIDevices
FROM netinfo_device_details
WHERE LoopBackAddress LIKE '10.12%' AND Status = 'Operational';
The SUM aggregation function really does a SUM of a set of numbers. COUNT just counts the number of rows.
Since the actual content of the row is not relevant, you can use COUNT(*) instead of COUNT(status) if you want.

how to return all rows when given value lies between two columns

its easier selecting a row whose value is between given number. But I m having no luck to figure out this-
I have a table in which there are two fields min_age and max_age. How to return all rows when given value lies between min_age and max_age
P.S. I m still a newbie in sql, please forgive me if this sounds too silly.
Thanks
SELECT *
FROM `tbl`
WHERE 35 BETWEEN `min_age` AND `max_age`;
That ought to do it. Of course, I used 35. You can use any other value instead.
You can use BETWEEN to get your desired result
SELECT *
FROM tablename
WHERE <some value> BETWEEN `min_age` AND `max_age`;
If you are trying to do the opposite, (provide a single value and find all the rows where the min and max age values bracket the provided value), then try
Select * From table
Where #myValue Between min_age And max_age
Based on your question this is my first thought:
select * from from YOUR_TABLE where VALUE > min_age AND VALUE < max_age
However, I think there maybe more to your question, if these is please elaborate.
You could also try to use the BETWEEN operator
SELECT * FROM Persons WHERE LastName BETWEEN 'Hansen' AND 'Pettersen'
http://www.w3schools.com/sql/sql_between.asp

MySQL select with subquery having replace

So I have a data with format like ;1;;2; and then I need to use this number in a query so I thought I'd convert it to 1,2 and use that in a IN condition. In my table, the result should return 2 rows but instead it is returning only 1 row.
My query is like this. The subquery return 1,2 with no problem but only 1 row is retrieve.
select *
from wt_lists
where id IN ((select replace (replace(sendto, ';;',','),';','')
from wt_stats where statsid IN (1)))
But when I try it with this. It returns the correct result, which in my case is 2 rows.
select *
from wt_lists
where id IN (1,2)
What am I missing here?
Comma delimited strings need to be explicitly defined in the query in order to be used in the IN clause - there's countless examples on SO where people need to use dynamic SQL to incorporate user submitted comma delimited strings.
That said, I have a solution using the FIND_IN_SET function:
SELECT DISTINCT wl.*
FROM WT_LISTS wl
JOIN (SELECT REPLACE(REPLACE(ws.sendto, ';;',','),';','') AS ids
FROM WT_STATS ws
WHERE ws.statsid = 1) x ON FIND_IN_SET(wl.id, x.ids) > 0
You are replacing the string:
';1;;2;'
To:
'1,2'
So, you SQL query looks like:
select * from wt_lists where id IN ('1,2') from wt_stats where statsid IN (1)
To use IN clause you need select different values in different rows.
I found this store procedure that does exactly what you need.
http://kedar.nitty-witty.com/blog/mysql-stored-procedure-split-delimited-string-into-rows/
I have not tested, but it is the way.
Obs: Like David said in the comments above, parsing the data in your application is a better way to do this.