一条语句怎么统计比例
表:Table1
Id type name
1 1 jack
2 1 tony
3 2 sum
4 3 luss
我想查出来的效果表:
percent
50%
75%
100%
也就是说: type=1的数量占总条数的50% , type=1加上type=2 占总条数的75% , type 1、2、3、就是100% 这样的语句怎么写
求高手解答,谢谢!!!!!!!
[解决办法]
CREATE TABLE #TEMP (Id INT,TYPE INT,NAME VARCHAR(10))
INSERT INTO #TEMP
SELECT 1,1,'jack' UNION ALL
SELECT 2,1,'tony' UNION ALL
SELECT 3,2,'sum' UNION ALL
SELECT 4,3,'luss'
;WITH a1 AS
(
SELECT TYPE,COUNT(*) SL,ROW_NUMBER() OVER(ORDER BY TYPE) RE
FROM #temp
GROUP BY TYPE
)
SELECT CAST(CAST(100.*(SELECT SUM(sl) FROM a1 WHERE re<=a.re)/(SELECT SUM(sl) FROM a1) AS INT) AS VARCHAR(3))+'%'
FROM a1 a
ORDER BY TYPE
CREATE TABLE #tb (Id INT,TYPE INT,NAME VARCHAR(10))
INSERT INTO #tb
SELECT 1,1,'jack' UNION ALL
SELECT 2,1,'tony' UNION ALL
SELECT 3,2,'sum' UNION ALL
SELECT 4,3,'luss'
;with cte as
(
select TYPE,COUNT(1) as num from #tb group by type
)
select str(cast(100.0*(select SUM(num) from cte t where t.TYPE<=a.TYPE)/b.total as int))+'%' as result
from cte a,(select COUNT(*) as total from #tb)b
drop table #tb
/*
result
50%
75%
100%
*/
--SQL2000代碼如下:
CREATE TABLE #tb (Id INT,TYPE INT,NAME VARCHAR(10))
INSERT INTO #tb
SELECT 1,1,'jack' UNION ALL
SELECT 2,1,'tony' UNION ALL
SELECT 3,2,'sum' UNION ALL
SELECT 4,3,'luss'
select str(cast(100.0*(select SUM(num) from (select TYPE,COUNT(1) as num from #tb group by type) t where t.TYPE<=a.TYPE)/b.total as int))+'%' as result
from (select TYPE,COUNT(1) as num from #tb group by type) a,(select COUNT(*) as total from #tb)b