试试这个,它现在可以在 MySQL 中使用。
select id, video, views, ((views / (select sum(views) from video)) * 100) as Percentagess
from video
这是表格:
CREATE TABLE IF NOT EXISTS `video` (
`ID` int(11) NOT NULL,
`Video` varchar(50) NOT NULL,
`Views` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table `video`
--
INSERT INTO `video` (`ID`, `Video`, `Views`) VALUES
(1, 'Hulk', 20),
(2, 'Jack', 30),
(3, 'The King', 24);
下面的代码适用于 SQL Server:
这是一个带有我刚刚写的临时表的游标。
声明 @total int set @total = (从视频中选择 sum(Views))
declare @videoid int
declare @video varchar(50)
declare @views int
declare @percentage decimal(18, 2)
IF EXISTS (SELECT * FROM tempdb.sys.tables WHERE NAME LIKE '%tmp%')
DROP TABLE #tmp
--create temporary table
CREATE TABLE #tmp (VideoID int, VideoTitle varchar(50), Views int, Percentage decimal(18, 2))
DECLARE @videoPercent CURSOR
SET @videoPercent = CURSOR FOR
select id, video, views
from video
OPEN @videoPercent
FETCH NEXT FROM @videoPercent INTO @videoid, @video, @views
WHILE @@FETCH_STATUS = 0
begin
set @percentage = (convert(decimal(18,2), @views) / convert(decimal(18,2), @total)) * 100;
insert into #tmp(VideoID, VideoTitle, Views, Percentage)
values(@videoid, @video, @views, @percentage);
FETCH NEXT FROM @videoPercent INTO @videoid, @video, @views
end
select * from #tmp
CLOSE @videoPercent
DEALLOCATE @videoPercent
这是表格:
CREATE TABLE [dbo].[Video](
[ID] [int] NOT NULL,
[Video] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[Views] [int] NOT NULL
)
用数据填写它,你准备好了。玩的开心。