mrobertini1239
mrobertini1239

Reputation: 107

MYSQL query average price

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?

Upvotes: 0

Views: 85

Answers (3)

ScaisEdge
ScaisEdge

Reputation: 133360

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);  

Upvotes: 0

Bernd Buffen
Bernd Buffen

Reputation: 15057

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))

Upvotes: 1

Norbert
Norbert

Reputation: 6084

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.

Upvotes: 0

Related Questions