我对sql server有点新,所以希望这不是太复杂的事情。如果我有一个包含大量数据的表格,这些数据显示已完成或不完整的记录......
表1
ID CATEGORY COMPLETE
1 reports yes
2 reports no
3 processes no
4 processes yes
5 reports no
6 events yes
...创建一个新字段的最佳方法是什么,以显示每个类别的完整百分比?
表2
ID CATEGORY PERCENTAGE
1 events 100%
2 processes 50%
3 reports 33%
任何帮助将不胜感激,谢谢。
答案 0 :(得分:3)
group by
类别列,并使用条件求和来获取分子中的complete = 'yes'
个案例。
select category,
100 * 1.0 * sum(case when complete = 'yes' then 1 else 0 end)/count(*) as pct
from tablename
group by category
答案 1 :(得分:2)
您可以使用窗口函数和const int GWL_STYLE = -16;
//No ScrollBar
const int LVS_NOSCROLL = 0x2000;
private bool noScrollBar = false;
public bool NoScrollBar
{
get { return noScrollBar; }
set
{
noScrollBar = value;
int style = (int)NativeMethods.GetWindowLong(Handle, GWL_STYLE);
if (noScrollBar)
{
NativeMethods.SetWindowLong(Handle, GWL_STYLE, style | LVS_NOSCROLL);
}
else
{
NativeMethods.SetWindowLong(Handle, GWL_STYLE, style & ~LVS_NOSCROLL);
}
}
}
:
PARTITION BY Category
的 LiveDemo
强>
插入第二个表:
SELECT DISTINCT Category,
[percentage] = ROUND(100 * SUM(CASE complete WHEN 'yes' THEN 1.0 ELSE 0.0 END)
OVER (PARTITION BY Category)/
COUNT(*) OVER (PARTITION BY Category),0)
FROM #tab;
的 LiveDemo2
强>
答案 2 :(得分:1)
我认为最简单的方法是使用avg()
:
select category,
avg(case when complete = 'yes' then 100.0 else 0 end) as pct
from tablename
group by category;
如果你想把它作为一个百分比的数字,你需要更多的字符串操作:
select category,
str(avg(case when complete = 'yes' then 100.0 else 0 end)) + '%' as pct
from tablename
group by category;
但是,我建议将值保留为数字。