请帮我创建SQL脚本

时间:2015-02-19 17:27:32

标签: sql sql-server-2008 join sum

我正在尝试加入这两个表并从表1中获取id#2的总和并将其与表2连接

TABLE # 1
customer  id amount
Nick      1    150
Jack      2    100
Jack      2    130
TABLE # 2
product   Typ   Date        id
Apple    Fruit  2/19/15     1
Banana   Fruit  2/19/15     2 

我希望看到的结果是获得了ID#2的金额。

customer  id amount  product      Typ     Date      id
Nick      1    150    Apple      Fruit   2/19/15     1
Jack      2    230    Banana     Fruit   2/19/15     2 

希望有道理,

2 个答案:

答案 0 :(得分:1)

首先根据Sum找到amount的{​​{1}}。

然后使用customer将结果加入table2以获得结果。试试这个。

ID

答案 1 :(得分:0)

我们可以使用 ROW_NUMBER() PARTITION BY 代替分组

DECLARE @TABLE1 TABLE(Customer varchar(100), Id int, Amount int)

INSERT INTO @TABLE1
SELECT 'Nick', 1, 150 UNION
SELECT 'Jack', 2, 100 UNION
SELECT 'Jack', 2, 130 

DECLARE @TABLE2 TABLE(Product varchar(100), Typ Varchar(20), [Date] date, Id int)

INSERT INTO @TABLE2
SELECT 'Apple', 'Fruit', '2/19/15', 1 UNION
SELECT 'Banana', 'Fruit', '2/19/15', 2  


SELECT * FROM
(
    SELECT Customer, id, SUM(Amount) OVER (PARTITION BY Id) Amount,
    ROW_NUMBER() OVER (PARTITION BY Id ORDER BY Id) RN
    FROM @TABLE1 
)
T1
JOIN @TABLE2 T2 ON T1.Id = T2.Id
WHERE RN = 1