Adding the numbers of characters in a record (mysql) - mysql

I need to add the number of characters that there are in each of records.
SELECT
CHAR_LENGTH(fiedl1) +
CHAR_LENGTH(fiedl2) +
CHAR_LENGTH(fiedl3) +
CHAR_LENGTH(fiedl4) +
CHAR_LENGTH(fiedl5) +
CHAR_LENGTH(fiedl6)
FROM mytable;
The above code is not valid because if a field contains NULL values then it returns NULL.

You can use the IFNULL Control Flow Function.
IFNULL(expr1,expr2)
If expr1 is not NULL, IFNULL() returns expr1; otherwise it returns expr2. IFNULL() returns a numeric or string value, depending on the context in which it is used.
Your query should be something like this:
SELECT
IFNULL(CHAR_LENGTH(fiedl1), 0) +
IFNULL(CHAR_LENGTH(fiedl2), 0) +
IFNULL(CHAR_LENGTH(fiedl3), 0) +
IFNULL(CHAR_LENGTH(fiedl4), 0) +
IFNULL(CHAR_LENGTH(fiedl5), 0) +
IFNULL(CHAR_LENGTH(fiedl6), 0)
FROM mytable;
Let me know if you have any doubts.

Try using IFNULL, like so:
IFNULL(CHAR_LENGTH(fiedl1), 0) ...

Related

Mysql and between\in range condition

We have x2 columns min and max. Each can be null or integer. When we start search throw table we cannot use BETWEEN command... Question is, how to find in range with this conditions
value is greater then min (if it's not null)
and
value is less then max (if it's not null)
and
value is in range of min and max (if they BOTH not null)
value - our integer number. As you can see we cannot use BETWEEN command.
So NULL means no limit. You can still use BETWEEN:
select *
from mytable
where #value between coalesce(minvalue, #value) and coalesce(maxvalue, #value);
Or simply AND:
select *
from mytable
where #value >= coalesce(minvalue, #value)
and #value <= coalesce(maxvalue, #value);
Or the very basic AND and OR:
select *
from mytable
where (#value >= minvalue or minvalue is null)
and (#value <= maxvalue or maxvalue is null);
Use this:
WHERE col BETWEEN COALESCE(min, -2147483648) AND COALESCE(max, 2147483647)
According to your logic, if either the min or max be NULL, then the restriction should be ignored. In the above WHERE clause, if min be NULL then col will always be greater than the lower boundary, assuming that col is an integer. Similar logic applies to the max condition.
The large (and small) numbers you see represent the largest and smallest possible values for an integer in MySQL.
Without the option of using BETWEEN, I would recommend using a simple WHERE-AND clause.
If null values are not allowed, you should use the COALESCE function
http://dev.mysql.com/doc/refman/5.7/en/comparison-operators.html#function_coalesce
Returns the first non-NULL value in the list, or NULL if there are no non-NULL values.
SELECT *
FROM SCORES
WHERE score >= COALESCE(min_score, score)
AND score <= COALESCE(max_score, score)
Here is a sample fiddle I created
http://sqlfiddle.com/#!9/306947/2/0
My solution Yii2 AR like
$query
->joinWith(['vacancySalary'])
->andWhere([
'and',
'IF (vacancy_salary.min IS NULL, ' . $this->salaryMin . ', vacancy_salary.min) >= ' . $this->salaryMin,
'IF (vacancy_salary.max IS NULL, ' . $this->salaryMin . ', vacancy_salary.max) <= ' . $this->salaryMin
]);
Simple answer is use IF condition and proper values.
ADDED:
Another way to go
$query
->joinWith(['vacancySalary'])
->andWhere($this->salaryMin . ' BETWEEN IF(vacancy_salary.min IS NULL, 0, vacancy_salary.min) AND IF(vacancy_salary.max IS NULL, 0, vacancy_salary.max)');

Convert decimal to euro currency in MYSQL

What is the best way to select a decimal value from the mysql database and convert it to an euro currrency in the mysql selection.
When i select "format(multiplier * (coalesce(Invoice.rent, 0) + coalesce(Invoice.furnished, 0) + coalesce(Invoice.gwe, 0) + coalesce(Invoice.service, 0) + coalesce(Invoice.gas, 0) + coalesce(Invoice.electricity, 0) + coalesce(Invoice.water, 0) + coalesce(Invoice.heat, 0) + coalesce(Invoice.tax, 0) + coalesce(Invoice.internet_tv, 0)) - coalesce(sum(Payment.amount),0),2)"
It returns a number like this 1,000.25 i want it to be 1.000,25 what is the best way to do this in MYSQL select query?
The documentation reveals that FORMAT() has up to three arguments (emphasis mine):
FORMAT(X,D[,locale])
Formats the number X to a format like '#,###,###.##', rounded to D
decimal places, and returns the result as a string. If D is 0, the
result has no decimal point or fractional part.
The optional third parameter enables a locale to be specified to be
used for the result number's decimal point, thousands separator, and
grouping between separators. Permissible locale values are the same as
the legal values for the lc_time_names system variable (see Section
10.7, “MySQL Server Locale Support”). If no locale is specified, the default is 'en_US'.
That could be a starting point. (You apparently want the format provided by the de_DE locale.)
Demo
In database you cant change default decimal separator from . to , for reason described here insert-non-english-decimal-points-in-mysql.
You can use this function to format your output value:
CREATE FUNCTION f_change_decimal_separator(num_value VARCHAR(16)) RETURNS VARCHAR(16)
BEGIN
DECLARE char_value VARCHAR(16);
SET char_value = REPLACE(num_value, ".", ";");
SET char_value = REPLACE(char_value, ",", ".");
SET char_value = REPLACE(char_value, ";", ",");
RETURN char_value;
END;

SQL: How do I sort on an alias calculated column ADD add a count?

I am new to SQL and having difficulty getting information out of my database, perhaps someone can provide guidance. I have
Table: students
Columns:
name, notes, test_1_score, test_2_score, test_3_score, test_4_score, test_5_score,
test_6_score, test_7_score, test_8_score, test_9_score, test_10_score
I can get the below code to run without the points_achieved in the GROUP BY but that is what I want to sort on. Also, I could not get the calculation to work without the IsNull added.
SELECT
name,
notes,
SUM (IsNull (test_1_score, 0) + IsNull (test_2_score, 0) + IsNull (test_3_score, 0) + IsNull (test_4_score, 0) + IsNull (test_5_score, 0) +IsNull ( test_6_score, 0) + IsNull (test_7_score, 0) + IsNull (test_8_score, 0) + IsNull (test_9_score, 0) + IsNull (test_10_score, 0)) AS points_acheived
FROM students
GROUP BY
points_achieved, name, notes;
Ultimately, I would like a simple answer to show:
name points_achieved (add a count of # tests completed)…….notes
Any help is greatly appreciated, thank you.
Try this:
SELECT
name,
notes,
SUM (IsNull (test_1_score, 0) + IsNull (test_2_score, 0) + IsNull (test_3_score, 0) + IsNull (test_4_score, 0) + IsNull (test_5_score, 0) +IsNull ( test_6_score, 0) + IsNull (test_7_score, 0) + IsNull (test_8_score, 0) + IsNull (test_9_score, 0) + IsNull (test_10_score, 0)) AS points_acheived
FROM students
GROUP BY
points_achieved, name, notes
order by 3;
You can take advantage of the fact that various boolean operators in SQL have the value 1 or 0 for true or false.
So the expression test_1_score IS NOT NULL will have the value 1 if that column has a valid value.
Use this query:
SELECT name, notes,
SUM(IsNull(test_1_score,0) + /* etc */) AS points_achieved
SUM((test_1_score IS NOT NULL) + (test_2_score IS NOT NULL) + /*etc*/) AS tests_taken
FROM students
GROUP BY name, notes

Incorrect parameter count in the call to native function 'ISNULL'

I have a query that I am trying to convert to MySQL from MS SQL Server 2008. It runs fine on MSSQL,
I get the error
"Incorrect parameter count in the call to native function 'ISNULL'".
How do I solve this?
SELECT DISTINCT
dbo.`#EIM_PROCESS_DATA`.U_Tax_year,
dbo.`#EIM_PROCESS_DATA`.U_Employee_ID,
CASE
WHEN dbo.`#EIM_PROCESS_DATA`.U_PD_code = 'SYS033' THEN SUM(dbo.`#EIM_PROCESS_DATA`.U_Amount)
END AS PAYE,
CASE
WHEN dbo.`#EIM_PROCESS_DATA`.U_PD_code = 'SYS014' THEN SUM(dbo.`#EIM_PROCESS_DATA`.U_Amount)
END AS TOTALTAXABLE,
dbo.OADM.CompnyName,
dbo.OADM.CompnyAddr,
dbo.OADM.TaxIdNum,
dbo.OHEM.lastName + ', ' + ISNULL(dbo.OHEM.middleName, '') + '' + ISNULL(dbo.OHEM.firstName, '') AS EmployeeName
FROM
dbo.`#EIM_PROCESS_DATA`
INNER JOIN
dbo.OHEM ON dbo.`#EIM_PROCESS_DATA`.U_Employee_ID = dbo.OHEM.empID
CROSS JOIN
dbo.OADM
GROUP BY dbo.`#EIM_PROCESS_DATA`.U_Tax_year , dbo.`#EIM_PROCESS_DATA`.U_Employee_ID , dbo.OADM.CompnyName , dbo.OADM.CompnyAddr , dbo.OADM.TaxIdNum , dbo.OHEM.lastName , dbo.OHEM.firstName , dbo.OHEM.middleName , dbo.`#EIM_PROCESS_DATA`.U_PD_code
MySQL
SELECT DISTINCT
processdata.taxYear, processdata.empID,
CASE WHEN processdata.edCode = 'SYS033' THEN SUM (processdata.amount) END AS PAYE,
CASE WHEN processdata.edCode = 'SYS014' THEN SUM (processdata.amount) END AS TOTALTAXABLE,
company.companyName, company.streetAddress, company.companyPIN, employeemaster.lastName + ', ' + IFNULL(employeemaster.middleName, '')
+ ' ' + IFNULL(employeemaster.firstName, '') AS EmployeeName
FROM
processdata INNER JOIN
employeemaster ON processdata.empID = employeemaster.empID
CROSS JOIN company
GROUP BY processdata.taxYear, processdata.empID, company.companyName, company.streetAddress, company.companyPIN,
employeemaster.lastName, employeemaster.firstName, employeemaster.middleName, processdata.edCode
The MySQL equivalent of ISNULL is IFNULL
If expr1 is not NULL, IFNULL() returns expr1; otherwise it returns
expr2.
Maybe also look at SQL NULL Functions
The ISNULL from MySQL is used to check if a value is null
If expr is NULL, ISNULL() returns 1, otherwise it returns 0.
I would suggest that you switch to the ANSI standard function coalesce():
(dbo.OHEM.lastName + ', ' + coalesce(dbo.OHEM.middleName, '') + '' + coalesce(dbo.OHEM.firstName, '')
) AS EmployeeName
You could also make your query easier to read by including table aliases.
EDIT:
As a note, I seemed to have missed the direction of conversion. The MySQL query would use concat():
CONCAT(OHEM.lastName, ', ', coalesce(OHEM.middleName, ''),
coalesce(concat(' ', OHEM.firstName), '')
) AS EmployeeName
I was getting an error when running JUnit tests against a query which had ISNULL(value) with the error saying ISNULL needed two parameters. I fixed this by changing the query to have value is null and the code works the same while the tests now work.

How to format int to price format in SQL?

I select the price 1000000 and I need to format it to $1,000,000. How can I do that in SQL?
To format with commas, you can use CONVERT with a style of 1:
declare #money money = 1000000
select '$' + convert(varchar, #money, 1)
will produce $1,000,000.00
If you want to remove the last 3 characters:
select '$' + left(convert(varchar, #money, 1), charindex('.', convert(varchar, #money, 1)) - 1)
and if you want to round rather than truncate:
select '$' + left(convert(varchar, #money + $0.50, 1), charindex('.', convert(varchar, #money, 1)) - 1)
Creating Function:
CREATE FUNCTION [dbo].[f_FormatMoneyValue]
(
#MoneyValue money
)
RETURNS VARCHAR(50)
AS
BEGIN
RETURN cast(#MoneyValue as numeric(36,2))
END
Using in Select Query:
Select dbo.f_FormatMoneyValue(isnull(SalesPrice,0))SalesPrice from SalesOrder
Output:
100.00
Formatting Money Value with '$' sign:
CREATE FUNCTION [dbo].[f_FormatMoneyWithDollar]
(
#MoneyValue money
)
RETURNS VARCHAR(50)
AS
BEGIN
RETURN '$' + convert(varchar, #MoneyValue, 1)
END
Output:
$100.00
Note: The above sample is for the money field. You can modify this function according to your needs
Hope this helps you..! :D
SELECT FORMAT(price, 'C2', 'en-us')
The SQL Server money datatype is just decimal(10, 4). To my knowledge there is no datatype that will present the way you want.
Adding the dollar sign and commas is something that should belong in the application logic, but if you really must do it through a database object consider adding the dollar sign, and commas every three characters (after the decimal point). In other words, you'll have to convert the int to varchar and do string manipulation.
It depends, however, there's no simple way to do it in standard SQL specs(SQL-92, SQL-2003, etc.).
For PostgreSQL PL/pgSQL and Oracle PL/SQL, you can use to_char to format numbers:
select to_char(1234567.123, 'FM$999,999,999.99')
Which gives output:
$1,234,567.12
See: http://www.postgresql.org/docs/7/static/functions2976.htm