I have a table with an index and I am executing a aggregate SQL query using sum
you can see what I am doing here in sqlfiddle.
Create table TX (
i int NOT NULL PRIMARY KEY,
x1 DECIMAL(7,3),
x2 DECIMAL(7,3),
x3 DECIMAL(7,3)
);
INSERT INTO TX (i,x1,x2,x3) values
(1,5, 6,6) ;
INSERT INTO TX (i,x1,x2,x3) values
(2,6, 7, 5);
INSERT INTO TX (i,x1,x2,x3) values
(3,5, 6, 7) ;
INSERT INTO TX (i,x1,x2,x3) values
(4,6, 7, 4);
My question is How can I insert into 3 different tables the results of that query?
SELECT SUM(1),
SUM(x1),SUM(x2),SUM(x3),
SUM(x1*x1),
SUM(x2*x1),SUM(x2*x2),
SUM(x3*x1),SUM(x3*x2),SUM(x3*x3)
FROM TX
so
how can I get something like
Sum(1)
-----
n
index Sums
------------
1 4
2 22
3 26
index1 index2 Mult
----------------------
1 1 122
2 1 144
2 2 170
3 1 119
3 2 141
3 3 126
Instead of
SUM(1) SUM(X1) SUM(X2) SUM(X3) SUM(X1*X1) SUM(X2*X1) SUM(X2*X2) SUM(X3*X1) SUM(X3*X2) SUM(X3*X3)
_____________________________________________________________________________________________________
4 22 26 22 122 144 170 119 141 126
SQL Fiddle using your data – Note that your data’s sums (second query) do not match those in your question. I trust this is a typo.
Notice I got a bit lazy with the third query. Instead of writing out the expansion I flattened the table first and joined it on itself.
Also note that in the first query
SUM(1)can be replaced withCOUNT(*).