SQL - 使用公共密钥在同一个表中减去2行

时间:2012-04-15 20:02:07

标签: sql tsql

拥有一个包含三列的数据库 - gamekey,teamed,final score。我试图找到每个游戏键的得分差异。

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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. 我想在ProductSold(数量)插入时从商店(数量)表中减去表格。