camilo soto
camilo soto

Reputation: 1271

mysql query with left outer join and average

I have two tables in mysql. The first table is names have the following dates:

    name           service         number
    carlos          telephone         6
    juan             watter          12
    maria             gas            23
    jhon             hostal          17
    marcos           sleeping        21
    carlos          othercarlos      12
    other             other          13

And i have other table alias

    name             service         alias              price
   carlos          telephone        telephone-carlos     700
   carlos          sleeping         sleeping-carlos      300  
    juan             watter          watter-juan         900
    maria             gas            gas-maria           650
    jhon             hostal          hostal-jhon         700

And i need a view with name, alias, number and prince. But i need all rows in name i intent with a left outer join. But the problem is that when i do the query when is othercarlos i need that the price will be the average of carlos services and when the name is other i need that appear the average of all services. But appear null

http://sqlfiddle.com/#!2/c1d4f/1

I create this tables and my query

Upvotes: 3

Views: 466

Answers (1)

Lamak
Lamak

Reputation: 70638

Ok, I'm sure that there are better ways to do this, but I can at least offer you one way:

SELECT  t1.name, 
        t1.service, 
        t2.alias, 
        t1.number, 
        COALESCE(t2.price,t3.price,t4.price) AS price
FROM name t1
LEFT JOIN alias t2
    ON t1.name= t2.name 
    AND t1.service = t2.service
LEFT JOIN ( SELECT name, AVG(price) AS price
            FROM alias
            GROUP BY name) t3
    ON t1.name = t3.name
LEFT JOIN ( SELECT AVG(price) AS price
            FROM alias) t4
    ON t1.name = 'other'

Here is a fiddle with this.

The result:

╔════════╦═════════════╦══════════════════╦════════╦═══════╗
║  NAME  ║   SERVICE   ║      ALIAS       ║ NUMBER ║ PRICE ║
╠════════╬═════════════╬══════════════════╬════════╬═══════╣
║ carlos ║ telephone   ║ telephone-carlos ║      6 ║   700 ║
║ juan   ║ watter      ║ watter-juan      ║     12 ║   900 ║
║ maria  ║ gas         ║ gas-maria        ║     15 ║   250 ║
║ jhon   ║ hostal      ║ hostal-jhon      ║     21 ║   640 ║
║ carlos ║ sleeping    ║ sleeping-carlos  ║     24 ║   300 ║
║ carlos ║ othercarlos ║ (null)           ║     11 ║   500 ║
║ other  ║ (null)      ║ (null)           ║      2 ║   558 ║
╚════════╩═════════════╩══════════════════╩════════╩═══════╝

Upvotes: 3

Related Questions