I have a table, Table1
Table1
ID REG VALUE
1 54 500
2 54 1700
3 60 5000
4 60 5500
Now, i need to copy rows from this table to a second one, Table2 , but for entries with the same REG
i want to make single row in the second table,with the difference between the highest VALUE
and the lower VALUE
, something like this:
Table2
ID REG VALUE
1 54 1200
2 60 500
How can I do this?
You could use an insert-select statement:
INSERT INTO table2 (reg, value)
SELECT reg, MAX(value) - MIN(value)
FROM table1
GROUP BY reg
HAVING COUNT(*) > 1
EDIT:
If the requirement is to also copy values that appear on a single reg
row too, this can be done using a case
expression:
INSERT INTO table2 (reg, value)
SELECT reg,
CASE COUNT(*) WHEN 1 THEN MAX(value) ELSE MAX(value) - MIN(value) END
FROM table1
GROUP BY reg
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.