从没有变量的单列计算百分比

时间:2013-07-13 09:28:04

标签: sql sql-server sql-server-2008 tsql

我在sql server中有以下表格

HEAD    | COL1  | COL2
------------------------
MARKS   | 546   | 798
TOTAL   | 1000  | 1000
PERCENT | NULL  | NULL

我想通过查询填充下面的结果。请帮帮我

HEAD    | COL1  | COL2
------------------------
MARKS   | 546   | 798
TOTAL   | 1000  | 1000
PERCENT | 54.6  | 79.8

2 个答案:

答案 0 :(得分:0)

不接受您的表格结构。它被逆转并伤害了我的眼睛。为您的表结构编写解决方案只能解决症状,我正在努力解决真正的问题。

CREATE TABLE Table1
([head] varchar(10), [marks] INT, [total] INT, [pct] as cast(100.0*marks / total as numeric(4,1)))

INSERT INTO Table1(head, marks, total)
VALUES ('Col1', 546, 1000),('Col2', 798, 1000)

SELECT head, marks, total FROM Table1

结果:

head  marks  total  pct
Col1  546    1000   54.6
Col2  798    1000   79.8

答案 1 :(得分:0)

update tablename set
col1 = c1, col2 = c2 from
(
Select x.col1*100./y.col1 c1, x.col2*100./y.col2 c2 from
(select * from TableName where head='mark') x
cross join 
(select * from TableName where head='total') y
 ) z
where head = 'percent';