SQL Query: Sum at end of each row and column
Problem:
I want to show sum of column and row at end. For E.G
Required Output :
DATE GURGAON INDORE TOTAL_ROW
2014/12/01 1889.93 1889.93
2014/12/02 1539.94 1299.96 2839.9
2014/12/03 2429.9 1299.92 3729.82
2014/12/04 499.98 749.94 1249.92
TOTAL_COL 6359.75 3349.82 9709.57
Input Table as
Date1 location Sale1
2014/12/01 GURGAON 1889.93
2014/12/02 GURGAON 1539.94
2014/12/02 INDORE 1299.96
2014/12/03 INDORE 1299.92
2014/12/03 GURGAON 2429.9
2014/12/04 GURGAON 499.98
2014/12/04 INDORE 749.94
Solution:
The best way is to use Pivot table:
--DROP TABLE #tmp
CREATE TABLE #tmp (Date1 DATE, location VARCHAR(30), Sale1 DECIMAL(8,2))
INSERT INTO #tmp (Date1, location, Sale1)
VALUES('2014/12/01', 'GURGAON', 1889.93),
('2014/12/02', 'GURGAON', 1539.94),
('2014/12/02', 'INDORE', 1299.96),
('2014/12/03', 'INDORE', 1299.92),
('2014/12/03', 'GURGAON', 2429.9),
('2014/12/04', 'GURGAON', 499.98),
('2014/12/04', 'INDORE', 749.94)
DECLARE @SumG DECIMAL(8,2)
SELECT @SumG = SUM(Sale1) FROM #tmp WHERE location = 'GURGAON'
DECLARE @SumI DECIMAL(8,2)
SELECT @SumI = SUM(Sale1) FROM #tmp WHERE location = 'INDORE'
SELECT DATE1, GURGAON, INDORE, COALESCE(GURGAON,0) + COALESCE(INDORE,0) AS SumOfRow
FROM (
SELECT *
FROM #tmp
) AS DT
PIVOT(SUM(Sale1) FOR location IN (GURGAON, INDORE )) AS PT
UNION ALL
SELECT NULL, @SumG AS GURGAON, @SumI AS INDORE, @SumG + @SumI
DROP TABLE #tmp
Result:DATE1 GURGAON INDORE SumOfRow
2014-12-01 1889.93 NULL 1889.93
2014-12-02 1539.94 1299.96 2839.90
2014-12-03 2429.90 1299.92 3729.82
2014-12-04 499.98 749.94 1249.92
NULL 6359.75 3349.82 9709.57
How do I get the total count over selected columns in my table?
I am trying to get the total count over selected columns in my table. I have 45 columns in my table. I need 43 of them summed and totaled for a counter. I can not seem to get this sql statement to work:
SELECT SUM([index],[01],[02],...,[at]) FROM [count];
The "..." are the rest of the 43 columns.
Soultion 1:
SELECT
(col1+ col2 + .... +coln) as ROWTOTAL
FROM
TABLENAME
Solution 2:
SUM is an aggregate, not a genaric function. I don't know get your final goal, but these are your options:
Simply use addition, to get the sum of specific culumn values. You will get as many rows as your selection gives:
SELECT [index]+[01]+[02]+...+[at] as [SUM] FROM [count];
You can summarize each column on it's own. You will get one row, with as many values, as many columns you add:
SELECT SUM([index]), SUM([01]), SUM([02]),...,SUM([at]) FROM [count];
And of course, you can combine these, to get the sum of all:
SELECT SUM([index]+[01]+[02]+...+[at]) as [SUM] FROM [count];
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home