我有一个数据库,我需要查询这个数据库来计算并总结篮球比赛中球员传球所产生的分数。例如,如果玩家传递给队友且该传球得到2分,我的数据库当前将其存储为某个表中的1个实例。如果传球得到3分,则存在另一个表格,存储数据。我想查询以便计算得出2分的玩家传球的所有实例然后再乘以2,并且计算得到3分的球员的传球的所有实例然后再乘以3。
以下是我的相关表格和选择陈述:
CREATE TABLE Passer(
PasserID int identity PRIMARY KEY not null
, Forename char(30) not null
, Surname char (30) not null)
CREATE TABLE Teammate(
TeammateID int identity PRIMARY KEY not null
, Forename char(30) not null
, Surname char(30) not null
, PasserID int FOREIGN KEY REFERENCES Passer(PasserID) not null)
CREATE TABLE TwoPointsFromShot(
TwoPointsFromShotID int identity PRIMARY KEY not null
, PasserID int FOREIGN KEY REFERENCES Passer(PasserID) not null
, TeammateID int FOREIGN KEY REFERENCES Teammate(TeammateID) not null)
CREATE TABLE ThreePointsFromShot(
ThreePointsFromShotID int identity PRIMARY KEY not null
, PasserID int FOREIGN KEY REFERENCES Passer(PasserID) not null
, TeammateID int FOREIGN KEY REFERENCES Teammate(TeammateID) not null
--First and Last Name of Passer from TwoPointsFromShot--
SELECT Forename, Surname
FROM Passer
JOIN TwoPointsFromShot ON TwoPointsFromShot.PasserID = Passer.PasserID
--First And Last name of Passer from ThreePointsFromShot--
SELECT Forename, Surname
FROM Passer
JOIN ThreePointsFromShot ON ThreePointsFromShot.PasserID = Passer.PasserID
当我从TwoPointsFromShot表中查询PasserID时,我收到的表格如下:
| PasserID
------------------- | --------
1 | 1
2 | 3
3 | 3
4 | 2
从ThreePointsFromShot表查询PasserID时,我收到类似的表。
| PasserID
--------------------- | --------
1 | 3
2 | 1
3 | 3
4 | 4
我想返回一个查询,该查询从TwoPointsFromShot计算PasserID的实例数,并将其乘以2,从ThreePointsFromShot计算PasserID的实例数,并将其乘以3,将这两个值相加,并替换PasserID与玩家的名字。所以它看起来像这样(如果Julius Randle是PlayerID 1,Dario Saric是PlayerID 2,TJ McConnell是PlayerID 3,Brandon Ingram是PlayerID 4):
| PasserName | PointsFromTwo | PointsFromThree | PassToPoints
--- | --------- | --------------- | ------------------ | ------------
1 | Julius Randle | 2 | 3 | 5
2 | Dario Saric | 2 | 0 | 2
3 | TJ McConnell | 4 | 6 | 10
4 | Brandon Ingram| 0 | 3 | 3
非常感谢任何帮助!
答案 0 :(得分:1)
我可以使用两个common table expressions来获得您想要的结果。
--CTE to get number of 2 pointers
WITH twoPointers AS
(
SELECT PasserId,COUNT(*) '2ptCount'
FROM TwoPointsFromShot
GROUP BY PasserID
),
--CTE to get number of 3 pointers
threePointers As
(
SELECT PasserId,COUNT(*) '3ptCount'
FROM ThreePointsFromShot
GROUP BY PasserID
)
--Join the Passer table with 2 CTE's and
--calculate results
SELECT RTRIM(Forename) + ' ' + RTRIM(Surname) AS 'PasserName',
ISNULL(two.[2ptCount] * 2, 0.00) AS 'PointsFromTwo',
ISNULL(three.[3ptCount] * 3, 0.00) AS 'PointsFromThree',
ISNULL(two.[2ptCount] * 2, 0.00) + ISNULL(three.[3ptCount] * 3, 0.00) AS 'PassToPoints'
FROM Passer p
LEFT JOIN twoPointers two ON p.PasserID = two.PasserID
LEFT JOIN threePointers three ON p.PasserID = three.PasserID