I am trying to get the percentage of two rows. I have a table1 as the below:
| Year | Col1 | Col2 |
| ------------ | ------------ | ------------ |
| Year 1 | 61 | 67 |
| Year 2 | 56 | 75 |
I need to get the percentage of the above two rows as the below:
| Year | Col1 | Col2 |
| ------------ | ------------ | ------------ |
| Year 1 % | 52.14% | 47.18% |
| Year 2 % | 47.86% | 52.81% |
I have used the below statement, but I am not able to get the percentage across like the above table:
SELECT
Year1
,[Col1], ([Col1] * 100) / (SELECT ISNULL(SUM([Col1]),0) FROM table1) AS Percentage
FROM table1
UNION ALL
SELECT
Year2
,Col2, ([Col2] * 100) / (SELECT ISNULL(SUM([Col2]),0) FROM table1) AS Percentage
FROM table1
Thanks in advance.
2条答案
按热度按时间ujv3wf0j1#
如果只是这两列,我会简单地
tyu7yeag2#
Another approach is taking advantage of window function:
outcome: