I have the next three tables:
Table A
| Client | Consumption1 | Consumption2 | ... | Consumption28 |
|---|---|---|---|---|
| 4587 | 325442 | 67420 | ... | 364855 |
| 1056 | 104687 | 35879 | ... | 8764501 |
| 8977 | 485236 | 68743 | ... | 477285 |
Table B
| Client | Arrive1 | Arrive2 | ... | Arrive28 |
|---|---|---|---|---|
| 4587 | 926842 | 474230 | ... | 634875 |
| 1278 | 154327 | 956948 | ... | 84868 |
| 8977 | 694826 | 2587474 | ... | 87547 |
Table C
| Client | Stock1 | Stock2 | ... | Stock28 |
|---|---|---|---|---|
| 4587 | 282 | 423 | ... | 875 |
| 1056 | 153 | 948 | ... | 886 |
| 8977 | 694 | 874 | ... | 854 |
I would want a table like this:
| Client | Stock | Consumption | Arrive |
|---|---|---|---|
| 4587 | 282 | 325442 | 926842 |
| 4587 | 423 | 67420 | 474230 |
| 4587 | ... | ... | ... |
| 4587 | 875 | 364855 | 634875 |
| 8977 | 694 | 485236 | 694826 |
| 8977 | 874 | 68743 | 474230 |
| 8977 | ... | ... | ... |
| 8977 | 854 | 477285 | 634875 |
I try the next code:
CREATE TABLE FINAL_TB AS (
SELECT CLIENT FROM TABLE_A );
ALTER TABLE FINAL_TB ADD STOCK FLOAT(20);
INSERT INTO FINAL_TB(STOCK) SELECT TABLE_C.STOCK1 FROM TABLE_C
UNION ALL
SELECT TABLE_C.STOCK2 FROM TABLE_C
...
UNION ALL
SELECT TABLE_C.STOCK28 FROM TABLE_C;
But i don't get the result I want and the code is so extensive. Any help?
I created some temp tables with random values to illustrate:
If you know that every possible
Clientvalue will exist in the Consumption table for example, you can just sum the fields and join the tables:If it's possible that a Client might exist in only one or two of the tables and you can't know which one(s), then you need to distinct list of clients first:
However, as has been pointed out in the comments, this table design seems pretty bad and should probably be changed, for example:
Or even:
In which case your query becomes much simpler: