选择不同的查询

时间:2018-08-23 13:33:16

标签: sql-server

我要检索以下格式的数据:

Category, Question, Status, Answer

我不想重复,所以我通过以下方式检索了唯一的类别,问题和状态:

select distinct category, question, status
from sharepoint_vw

但是我想有一个额外的列作为“ Answer”,作为由表达式计算得出的%值:

=SUM(IIF(Fields!Status.Value="Unfavourable",1,0))/COUNT(Fields!Status.Value)

我只是不知道如何将该表达式转换为SQL并将其与选择的不同查询组合以获得我需要的结果。

2 个答案:

答案 0 :(得分:1)

类似:

select category, question
avg(case status when 'unfavorable' then 1.0 else 0.0 end) as avgunfavorable
from sharepoint_vw
group by  category, question

答案 1 :(得分:0)

如果您确实希望将状态作为SQL输出的一部分,则必须汇总子查询中每个category, question的总数。然后,您可以在主查询中的计算中使用该总数:

SELECT DISTINCT
  sharepoint_vw.category,
  sharepoint_vw.question,
  sharepoint_vw.status,
  count(*)/total.rcount as answer
FROM sharepoint_vw
  LEFT OUTER JOIN 
    (
       SELECT 
         category, 
         question,          
         CAST(COUNT(*) AS DECIMAL(10,2)) as rcount 
       FROM sharepoint_vw 
       GROUP BY category, question
     ) as total
       ON sharepoint_vw.category = total.category
         AND sharepoint_vw.question = total.question
GROUP BY 
  sharepoint_vw.category,
  sharepoint_vw.question,
  sharepoint_vw.status,
  total.rcount

answer列现在将保存每个status的百分比。您可以在this sqlfiddle

上看到其实际效果

值得一提的是,我们在这里处理整数(计数和),因此我们必须将其中至少一个强制转换为Decimal()类型,否则您将只获得整数返回值。