2012-04-15 18 views
0

擁有包含三列的數據庫 - gamekey,組隊,最​​終得分。我試圖找出每個遊戲鍵的分數差異。SQL - 使用公共密鑰在同一表中減去2行

 
Gamekey. Teamed. Finalscore 
16  27  21 
16  7  24 
17  22  17 
17  21  10 
18  15  9 
18  11  3 

慾望輸出將

 
Gamekey. Scorediff 
16   3 
17   7 
18   6 
+3

分數差分是如何計算的?我沒有看到輸入和輸出之間的相關性。 – Oded 2012-04-15 20:04:51

+0

你對每個Gamekey總是有兩行嗎? – 2012-04-15 20:05:33

+0

順便說一句 - 我從來沒有真正希望看到一個答案接受userXXXXXXX 1代表接受。 user1334995,證明我錯了;) – 2012-04-15 22:27:45

回答

5

看起來像你想的差的絕對值,所以你可以使用;

SELECT Gamekey, max(Finalscore) - min(Finalscore) as Scorediff 
FROM TableName 
GROUP BY Gamekey 

- 增加了下面的驗證你跑(授予以下是在SQL Server的測試)

declare @testTable as table(Gamekey int, Teamed int, Finalscore int) 

INSERT INTO @testTable values(16,27,21) 
INSERT INTO @testTable values(16,7,24) 
INSERT INTO @testTable values(17,22,17) 
INSERT INTO @testTable values(17,21,10) 
INSERT INTO @testTable values(18,15,9) 
INSERT INTO @testTable values(18,11,3) 


SELECT Gamekey, max(Finalscore) - min(Finalscore) as Scorediff 
FROM @testTable 
GROUP BY Gamekey 
+0

@Oded--請解釋你看到的問題 – 2012-04-15 20:09:03

+0

抱歉誤讀了這個問題 - 我以爲團隊參與了......我的錯誤。 – Oded 2012-04-15 20:17:25

+0

順便說一句伊恩尼爾森有一個好點。我假設輸入中的每個GameKey有兩行,如OP – 2012-04-15 20:17:44

1
Create table Shop 
(
    ItemCode varchar(10)not null, 
    ShopName Varchar(50) not null, 
    Items varchar(50) not null, 
    Quantity int not null, 
    OrderDate datetime NOT NULL DEFAULT GETDATE(), 
    UpdateDate varchar(11)not null 
) 
GO 

Create Table Product 
(
    ProductCode varchar(10)Primary key, 
    ShopName varchar(50), 
    Product varchar(50), 
    Quantity int , 
    UnitPrice money , 
    Defects int , 
    Remainders int , 
    TotalPrice money , 
    Benefit money , 
    OrderDate datetime NOT NULL DEFAULT GETDATE(), 
    UpdateDate varchar(11) 
) 
GO 
Create Table ProductSold 
(
    ShopName varchar(50)not null, 
    Product varchar(50) not null, 
    Quantity int not null, 
    UnitPrice money not null, 
    TotalPrice money not null, 
    OrderDate datetime NOT NULL DEFAULT GETDATE() 
) 
  1. 我想從產品(餘數)當店(減去數量)表插入到其表中。
  2. 我想從Shop(Quantity)表中減去ProductSold(Quantity)插入時的值。
+0

這是如何回答這個問題的? – 2012-11-26 17:02:16