Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server SQL-嵌套选择和透视_Sql Server_Sql Server 2008_Tsql - Fatal编程技术网

Sql server SQL-嵌套选择和透视

Sql server SQL-嵌套选择和透视,sql-server,sql-server-2008,tsql,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

我有这张桌子:

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 
((res.T - (res.F*(@FactorA/@FactorB)))*100)/count(res.lsn_id))
现在我编写这个select查询:

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
表格填充:

运行此查询时:

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

问题: 我想在第二个表中添加一列来计算 这个公式:

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


-- count(res.lsn_id) : count number of Question per lesson 
((res.T - (res.F*(@FactorA/@FactorB)))*100)/count(res.lsn_id))
像这样:

运行此查询时:

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
消息错误:

Msg 8120,级别16,状态1,第122行列'res.lsn_id'无效 在选择列表中,因为它不包含在任何聚合中 函数或GROUPBY子句


您可以将公式更改为:

((res.T - (res.F*(@FactorA/@FactorB)))*100)/count(*) OVER (ORDER BY (SELECT 1)))
每一行都有自己的
lsn\u id
,因此您可以使用OVER子句计算所有行。

对于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

谢谢,您的代码是正确的,在
count(*)over()
上有错误,但没问题,我修改了我的代码,发现我可以用
pvt.[T]+pvt.[F]+pvt.[W]
替换
count(*)over()
。现在,它的执行没有错误。