I have two mysql (5.6) views. One view contains only one value in one row from on column. Let's say is column A and in that single row i have the value 5000.
I have a second view with 3 columns: item (varchar), date (obviously containing dates) and value (decimal). This second view has 4 rows so it looks like this:
item date value
'lectii de pian', '2015-11-09', '101.88'
'Microsoft office','2015-11-11', '7.00'
'Belasting', '2015-11-15', '524.00'
'Netflix', '2015-11-18', '8.99'
What i want to do is to create in this view another column let's call it "B" and subtract the first value in column value from the value in view A and then from the result subtract the next value and so on so that it looks like this
item date value B
'lectii de pian', '2015-11-09', '101.88' '4898.12'
'Microsoft office','2015-11-11', '7.00' '4891.12'
'Belasting', '2015-11-15', '524.00' '4367.12'
'Netflix', '2015-11-18', '8.99' '4358.13'
Any ideas How i could achieve that in mysql 5.6?
Many thanks!
答案 0 :(得分:0)
Use a @variable
to hold the running subtraction, initializing it from view A.
SELECT b.item, b.date, b.value, @running := @running - value AS b
FROM view2 AS b
CROSS JOIN (SELECT @running := a FROM view1) AS a
ORDER BY b.date
答案 1 :(得分:0)
Sample data:
CREATE TABLE t1
(`item` varchar(50), `date` date, `value` decimal(6,2))
;
INSERT INTO t1
(`item`, `date`, `value`)
VALUES
('lectii de pian,', '2015-11-09,', 101.88),
('Microsoft office', '2015-11-11,', 7.00),
('Belasting,', '2015-11-15,', 524.00),
('Netflix,', '2015-11-18,', 8.99)
;
CREATE TABLE t2
(`a` int)
;
INSERT INTO t2
(`a`)
VALUES
(5000)
;
Query:
SELECT
t1.*,
@v := @v - `value` AS B
FROM
t1
, (SELECT @v := (SELECT MAX(a) FROM t2)) var_init_subquery
ORDER BY `date`
Result:
| item | date | value | B |
|------------------|----------------------------|--------|---------|
| lectii de pian, | November, 09 2015 00:00:00 | 101.88 | 4898.12 |
| Microsoft office | November, 11 2015 00:00:00 | 7 | 4891.12 |
| Belasting, | November, 15 2015 00:00:00 | 524 | 4367.12 |
| Netflix, | November, 18 2015 00:00:00 | 8.99 | 4358.13 |