0

假设我有一个名为“myPlayerInfo”的表,其中包含以下行

'player name' 'number of goals'
'john'        '10'
'martin'      '20'
'jen'         '20'

Q1。如何编写一个 sql 查询来打印一个新列,该列是“目标数”列的总和?

'player name' 'number of goals'  'Total goals by all players'
'john'        '10'               '50'
'martin'      '20'               '50'
'jen'         '20'               '50'

Q2。如何编写一个 sql 查询来打印一个新列,该列是每个球员的进球百分比以及我们在第一季度所做的总进球数列。?

'player name' 'number of goals' '% goals scored'  'Total goals by all players'
'john'        '10'              '20'                  '50'
'martin'      '20'              '40'                  '50'
'jen'         '20'              '40'                  '50'
4

3 回答 3

6

您需要使用窗口函数:

select
    player_name,
    number_of_goals,
    (number_of_goals * 100) / SUM(number_of_goals) OVER () AS percent_goals_scored,
    SUM([number of goals]) OVER () AS total_goals_by_all_players
from myPlayerInfo
于 2012-07-22T06:48:00.657 回答
3

您可以对从子选择派生的所有行的总和执行笛卡尔连接:

SELECT 
    a.player_name, 
    a.number_of_goals, 
    (a.number_of_goals / b.goalsum)*100 AS percent_scored,
    b.goalsum
FROM   
    myPlayerInfo a
CROSS JOIN 
    (SELECT SUM(number_of_goals) AS goalsum FROM myPlayerInfo) b
于 2012-07-22T06:50:12.513 回答
0

你的意思是像SELECT name, goals, sum(goals) as sum, goals/sum(goals) as relgoals FROM table;

于 2012-07-22T06:47:18.777 回答