MYSQL query average price - mysql

I have to calculate the average price of a house in Groningen.
Though the price is not stored as an number but as a string (with some additional information) and it uses a point ('.') as a thousands separator.
Price is stored as 'Vraagprijs' in Dutch.
The table results are:
€ 95.000 k.k.
€ 116.500 v.o.n.
€ 115.000 v.o.n.
and goes so on...
My query:
'$'SELECT AVG(SUBSTRING(value,8,8)) AS AveragePrice_Groningen
FROM properties
WHERE name = 'vraagprijs'
AND EXISTS (SELECT *
FROM estate
WHERE pc_wp LIKE '%Groningen%'
AND properties.woid = estate.id);
The result is:
209.47509187620884
But it has to be:
20947509187620,884
How can i get this done?

The AVG(SUBSTRING(value,8,8)) dosent work:
sample
MariaDB [yourSchema]> SELECT *,SUBSTRING(`value`,8,8), SUBSTRING_INDEX(SUBSTRING_INDEX(`value`, ' ', -2),' ',1) FROM properties;
+----+-----------------------+------------------------+----------------------------------------------------------+
| id | value | SUBSTRING(`value`,8,8) | SUBSTRING_INDEX(SUBSTRING_INDEX(`value`, ' ', -2),' ',1) |
+----+-----------------------+------------------------+----------------------------------------------------------+
| 1 | € 95.000 k.k. | 95.000 k | 95.000 |
| 2 | € 116.500 v.o.n. | 116.500 | 116.500 |
| 3 | € 115.000 v.o.n. | 115.000 | 115.000 |
+----+-----------------------+------------------------+----------------------------------------------------------+
3 rows in set (0.00 sec)
MariaDB [yourSchema]>
**change it to **
AVG(SUBSTRING_INDEX(SUBSTRING_INDEX(`value`, ' ', -2),' ',1))

Try using a CAST DECIMAL and SPLIT for get the right part of the string
'$'
SELECT AVG( CAST(SPLIT_STR(value,' ', 2)) AS DECIMAL) AS AveragePrice_Groningen
FROM properties
WHERE name = 'vraagprijs'
AND EXISTS (SELECT *
FROM estate
WHERE pc_wp LIKE '%Groningen%'
AND properties.woid = estate.id);

You entered the data with the . as decimal separator, which is normal in Dutch, but not normal in English where they tend to use the , as decimal separator.
Enter the data into you database as 215000.000, etc and you should get normal values as answer.

Related

Creating a column being the multiple of others

I need some help. I have 2 colluns from mysql query result: 1 with text, and another with decimal values. Like that:
select desc, value from table a
|5,50 % | 2984.59 |
|Subs | 10951.70 |
|Isent | 3973.17 |
|13,30 % | 560.26 |
From the rows that have the %, I want to multiply the values and create a third result column, rounding up to two decimal places. See above
2984,59 * 0,055 = 164,15245
560,26 * 0,133 = 74,514
I need make the sql query that show something like above.
+-------+-----------+-----------+
|5,50 % | 2984,59 | 164,16 |
|Subs | 10951,70 | 0 or NULL |
|Isent | 3973,17 | 0 or NULL |
|13,30% | 560,26 | 74,52 |
+-------+-----------+-----------+
How i can do it?
Thanks so much for help
It would be better to have floaring numbers in the first place, converting costs time
You have commas in your procentage, but mysql needs dots there
If value isn't always a number, you can use the mysql way to add a 0 0 to it, that remioves all non numerical characters
SELECT `desc`, `value`, (REPLACE(`desc`,',','.') + 0) * `value` / 100 FROM val
desc
value
(REPLACE(`desc`,',','.') + 0) * `value` / 100
5,50 %
2985
164.175
Subs
10952
0
Isent
3973
0
13,30 %
560
74.48
fiddle
SELECT `desc`, `value`, CEIL((REPLACE(`desc`,',','.') + 0) * `value`) / 100 FROM val
desc
value
CEIL((REPLACE(`desc`,',','.') + 0) * `value`) / 100
5,50 %
2985
164.18
Subs
10952
0
Isent
3973
0
13,30 %
560
74.48
fiddle

MySQL Question - I want to eliminate all text within any parenthesis

Just checking to see if any of you would have a solution for this – from the below text like this I want to eliminate all text within any parenthesis.
Input –
PAY - addition,FILES (aaaaaaaaaaaaaa/bbbbbbbbbbbs i.e. ssss,ffff – i.e. cccccc),DED (ppppppp, llllll, fffff gggg),LOSS (ddddd, hhhhhh – i.e.),F TO G ( “F” is switching to “G”)
Output –
PAY - addition,FILES,DED,LOSS,F TO G
If you are running MySQL 8.0, you can do this with regexp_replace():
regexp_replace(mytext, '\\([^)]*\\)', '')
This works as long as there are no nested parentheses in the expression (which is consistent with your sample data).
Demo on DB Fiddle:
select regexp_replace(
'PAY - addition,FILES (aaaaaaaaaaaaaa/bbbbbbbbbbbs i.e. ssss,ffff – i.e. cccccc),DED (ppppppp, llllll, fffff gggg),LOSS (ddddd, hhhhhh – i.e.),F TO G ( “F” is switching to “G”)',
'\\([^)]*\\)',
''
) val
| val |
| :--------------------------------------- |
| PAY - addition,FILES ,DED ,LOSS ,F TO G |
Another on for MYSQL8.0:
SET #input:="PAY - addition,FILES (aaaaaaaaaaaaaa/bbbbbbbbbbbs i.e. ssss,ffff – i.e. cccccc),DED (ppppppp, llllll, fffff gggg),LOSS (ddddd, hhhhhh – i.e.),F TO G ( “F” is switching to “G”)";
with recursive cte as (
select
0 i,
#input as text
union all
select
i+1,
CASE WHEN instr(text,'(') >0 AND instr(text,')')>instr(text,'(') THEN REPLACE(text, substring(text,instr(text,'('),instr(text,')')-instr(text,'(')+1), '') ELSE '' END
from cte
where i<10
) select text from cte where text<>'' order by i desc limit 1;
output:
+------------------------------------------+
| text |
+------------------------------------------+
| PAY - addition,FILES ,DED ,LOSS ,F TO G |
+------------------------------------------+
1 row in set (0.00 sec)

Two things to do in MySQL IF()

I have a problem concerning the IF() function in MySQL.
I would like to return a string and change the value of a variable. Somwhat like:
IF(#firstRow=1, "Dear" AND #firstRow:=0, "dear")
This outputs only '0' instead of 'Dear'...
I would be very thankful for some input on ways I could solve this problem!
Louis :)
AND is a boolean operator, not a "also do this other thing" operator.
"Dear" AND 0 returns 0 because 0 is treated as false in MySQL and <anything> AND false will return false.
Also because the integer/boolean value of "Dear" is 0 as well. Using a string in a numeric context just reads initial digits in the string, if any, and ignores the rest.
It's not clear what your problem is, but I guess you want to capitalize the word "dear" if the row is the first one in the result set.
Instead of being too clever by half trying to fit the side-effect into your expression, do yourself a favor and break it out into a separate column:
mysql> SELECT IF(#firstRow=1, 'Dear', 'dear'), #firstRow:=0 AS _ignoreThis
-> FROM (SELECT #firstRow:=1) AS _init
-> CROSS JOIN
-> mytable;
+---------------------------------+-------------+
| IF(#firstRow=1, 'Dear', 'dear') | _ignoreThis |
+---------------------------------+-------------+
| Dear | 0 |
| dear | 0 |
| dear | 0 |
+---------------------------------+-------------+
But if you really want to make your code as confusing and unreadable as possible, you can do something like this:
SELECT IF(#firstRow=1, CONCAT('Dear', IF(#firstRow:=0, '', '')), 'dear')
FROM (SELECT #firstRow:=1) AS _init
CROSS JOIN
...
But remember this important metric of code quality: WTFs per minute.
Use a case expression instead of IF() as the syntax is far easier to follow e.g.
select
case when #firstRow = 1 then 'Dear' else 'dear' end AS Salutation
, #firstRow := 0
from (
select 1 n union all
select 2 n union all
select 3
) d
cross join (SELECT #firstRow:=1) var
+---+------------+----------------+
| | Salutation | #firstRow := 0 |
+---+------------+----------------+
| 1 | Dear | 0 |
| 2 | dear | 0 |
| 3 | dear | 0 |
+---+------------+----------------+
Demo

split characters and numbers in MySQL

I have a column in my table like this,
students
--------
abc23
def1
xyz567
......
and so on. Now i need output like only names
Need output as
students
--------
abc
def
xyz
How can i get this in mysql. Thanks advance.
You can do it with string functions ans some CAST() magic:
SELECT
SUBSTR(
name,
1,
CHAR_LENGTH(#name) - CHAR_LENGTH(
IF(
#c:=CAST(REVERSE(name) AS UNSIGNED),
#c,
''
)
)
)
FROM
students
for example:
SET #name:='abc12345';
mysql> SELECT SUBSTR(#name, 1, CHAR_LENGTH(#name) - CHAR_LENGTH(IF(#c:=CAST(REVERSE(#name) AS UNSIGNED), #c, ''))) AS name;
+------+
| name |
+------+
| abc |
+------+

MySQL data transfer with re-formatting

I have this table synonym_temp:
id | synonyms
----------------------------
1 | ebay,online,dragon
2 | auto, med
And I want to transfer it to synonym table but each synonym should be inserted separately. Like:
id | synonym
----------------------------
1 | ebay
1 | online
1 | dragon
2 | auto
2 | med
How should I do that? Thanks in advance.
Use PHP
$records=mysql_query("select * from synonm_temp");
foreach($records as $row)
{
$synonums=$row['synonyms'];
$synonums_array=explode(',', $synonums);
$id=$row['id'];
foreach($synonums_array as $syn)
{
mysql_query("insert into synonm_temp values ($id,'$syn') ");
}
}
You can do this with a Numbers or Tally table which contains a sequential list of integers:
Select T.id, Substring(T.synonym, N.Value, Locate(', ', T.synonym+ ', ', N.Value) - N.Value)
From Numbers As N
Cross Join MyTable As T
Where N.Value <= Len(T.synonym)
And Substring(', ' + T.synonym, N.Value, 1) = ', '
In the above case, my Numbers table is structured like so:
Create Table Numbers( Value int not null primary key )