我的表格如下:
Cell Date Hour Minute Counter Value
AB1 20141008 14 15 C1 40
AB1 20141008 14 15 C2 15
AB1 20141008 14 30 C1 30
AB1 20141008 14 30 C2 13
我需要计算公式PERCENT,如果数据是水平的,C1,C2是列,则看起来像这样:
SELECT SUM(C2)/SUM(C1) as 'PERCENT'
FROM [Table]
group by Cell, Date, Hour
我正在考虑使用OVER Clause,但我不确定如何在这里实现它。
在下面的情况中,结果将是:
Cell Date Hour PERCENT
AB1 20141008 14 0.40 (Total of C2 = 28 / Total of C1 = 70)
感谢。
答案 0 :(得分:3)
如果数据是水平的,C1,C2是列
您可以将数据PIVOT来实现:
SELECT
Cell, Date, Hour,
SUM([C2])*100/SUM([C1]) AS [%],
SUM([C2])/CAST(SUM([C1]) AS DECIMAL(10,5)) AS [Percent]
FROM TABLE1
PIVOT (SUM(value) FOR Counter in ([C1],[C2]) ) AS pvt
GROUP BY Cell, Date, Hour
输出:
| CELL | DATE | HOUR | % | PERCENT |
|------|----------|------|----|---------|
| AB1 | 20141008 | 14 | 40 | 0.4 |
答案 1 :(得分:2)
你这样做:
SELECT Cell, Date, Hour,
SUM(CASE WHEN Counter = 'C2' THEN Value ELSE 0 END) /
SUM(CASE WHEN Counter = 'C1' THEN Value ELSE 0 END) AS Percent
FROM [table]
group by Cell, Date, Hour
答案 2 :(得分:1)
使用CASE并尝试此
SELECT Cell,
Date,
Hour,
SUM(CASE WHEN Counter = 'C1' THEN Value
ELSE 0
END )/
SUM(CASE WHEN Counter = 'C2' THEN Value
ELSE 0
END) AS 'PERCENT'
FROM Table
GROUP BY Cell, Date, Hour