SQL - 嵌套的select和Pivot

时间:2016-06-23 09:34:49

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

我有这张桌子:

create table #tmpState
(   sheet_id int, -- person sheet id
    qnumber int, -- Question number
    lsn_id int, -- lesson Id
    qstate nvarchar(1) -- 'T' ,  'F' , 'W'
)

我想计算这个公式:

(((res.T - (res.F*(@FactorA/@FactorB)))*100)/count(res.lsn_id)) as lsnpercent


-- count(res.lsn_id) : count number of Question per lesson 

现在我写这个选择查询:

select  * ,
   (((res.T - (res.F*(@FactorA/@FactorB)))*100)/count(res.lsn_id)) as lsnpercent
from (select * 
     from
     (select lsn_id , qstate from #tmpState ) as s
     pivot 
     (
         count(qstate)
         for [qstate] in (T,F,W)
     ) as pvt
     ) as res

#tmpState表填充:

<code>#tmpState</code> table :

当我运行此查询时:

select * 
 from
 (select lsn_id , qstate from #tmpState ) as s
 pivot 
 (
     count(qstate)
     for [qstate] in (T,F,W)
 ) as pvt

结果是:

enter image description here

问题: 我想将Column添加到第二个计算表中 这个公式:

((res.T - (res.F*(@FactorA/@FactorB)))*100)/count(res.lsn_id))
像这样:

enter image description here

运行此查询时

select  * ,
   (((res.T - (res.F*(@FactorA/@FactorB)))*100)/count(res.lsn_id)) as lsnpercent
from (select * 
     from
     (select lsn_id , qstate from #tmpState ) as s
     pivot 
     (
         count(qstate)
         for [qstate] in (T,F,W)
     ) as pvt
     ) as res

消息错误:

  

消息8120,级别16,状态1,行122列'res.lsn_id'无效   在选择列表中,因为它不包含在聚合中   函数或GROUP BY子句。

2 个答案:

答案 0 :(得分:1)

您可以将公式更改为:

((res.T - (res.F*(@FactorA/@FactorB)))*100)/count(*) OVER (ORDER BY (SELECT 1)))

每一行都有自己的lsn_id,因此您可以使用OVER子句计算所有行。

答案 1 :(得分:1)

对于SQL Server 2008 R2(SP3),您必须使用

select  pvt.[lsn_id], pvt.[T], pvt.[F], pvt.[W]
        ,[lsnpercent] = ((pvt.[T] - (pvt.[F] * (@FactorA/@FactorB))) * 100)/count(*) over()
from (select [lsn_id], [qstate] from #tmpState) as s
pivot (count(s.[qstate]) for s.[qstate] in ([T], [F], [W])) as pvt