Вопрос

I have this table:

DATE         ENGINEERS
----------------------
2014-03-06   6
2014-03-10   7

In which I register when the number of engineers change. For example, in this case I had 6 engineers, but on the 10th March, I hired one more, so I have 7 from then onwards.

I have another table with the appointments per day

DATE         APPOINTMENTS
-------------------------
2014-03-06   4
2014-03-07   5
2014-03-10   5
2014-03-11   6 

How can I get a view like this, which combines the appointments and the number of engineers per day?

DATE         APPOINTMENTS    ENGINEERS
--------------------------------------
2014-03-06   4               6
2014-03-07   5               6
2014-03-10   5               7
2014-03-11   6               7
Это было полезно?

Решение

This is what I could do :

SELECT t2.at, t2.appointments, (@n := IFNULL(t1.engineers, @n)) FROM t2
LEFT JOIN (
  SELECT t.at, t1.engineers
  FROM t1
  JOIN t2 t ON t1.at = t.at
) t1 ON t1.at = t2.at;

I am sure there is something better out there, as the redondant JOIN could not be needed, but I could not find it.

It actually use a sql variable to get the last value if there is no corresponding entry in the engineers table.

Don't forget to run SET @n = 0;.

The corresponding sqlfiddle.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top