比较一个表中的2个列值与第二个表sql server中的另一个列值的总和

时间:2017-12-04 19:13:08

标签: sql sql-server tsql

我有两张桌子......

table1(id,item,price)值:

id | item | price
-------------
10 | book | 20  
20 | copy | 30   
30 | pen  | 10

.... table2(id,item,price)值:

id | item | price
-------------
10 | book | 20
10 | book | 30

现在我如果在表1中没有id-10,item-book和(20 + 30)的记录,那么我想在新表中插入总和(20 + 30)的行。

2 个答案:

答案 0 :(得分:0)

尝试以下

SELECT T2.id,T2.item,T2.Price as Table2_Price,T1.Price as Table1_Price FROM (
SELECT id,Item,Sum(Price) as Price
FROM Table2
Group BY id,Item ) AS T2 LEFT JOIN Table1 AS T1
ON T1.Item = T2.Item and T1.ID = T2.ID

在阅读 when sum of these two not equals the one in another table it should return the sum from table 2 的评论后,您要求提供以下逻辑

SELECT T2.id,T2.Item, CASE WHEN T1.Price IS NULL THEN T2.Price 
                           WHEN T2.Price <> T1.Price THEN T2.Price 
                           ELSE T1.Price END as Price FROM (
SELECT id,Item,Sum(Price) as Price
FROM Table2
Group BY id,Item ) AS T2 LEFT JOIN Table1 AS T1
ON T1.Item = T2.Item and T1.ID = T2.ID

但是这个逻辑没有用,因为如果Sum(Table2_price) <> Table1_Price想要在Sum(Table2_price) Sum(Table2_price) = Table1_Price Table1_Price时选择Sum(Table2_Price) !!因此,您希望始终选择MATCH p=allShortestPaths( (u1{name:1174}) - [*..20] - (u2{name:1179}) ) return p

答案 1 :(得分:0)

如果我没有误解你的要求,应该这样做:

 SELECT T2.ID, T2.ITEM,T2.SUMPRICE FROM 
 (SELECT ID, ITEM, SUM(PRICE) AS SUMPRICE FROM table1 GROUP BY ID, ITEM) AS T1
 INNER JOIN 
 (SELECT ID, ITEM, SUM(PRICE) AS SUMPRICE FROM table2 GROUP BY ID, ITEM) AS T2
 ON T1.ID = T2.id  AND T1.item = T2.item WHERE T1.SUMPRICE <> T2.SUMPRICE 

如果已创建第3个表,则可以使用INSERT INTO SELECT语句。否则你可以使用这样的SELECT INTO

SELECT T2.ID, T2.ITEM,T2.SUMPRICE as price into table3 FROM 
(SELECT ID, ITEM, SUM(PRICE) AS SUMPRICE FROM table1 GROUP BY ID, ITEM) AS 
T1
INNER JOIN 
(SELECT ID, ITEM, SUM(PRICE) AS SUMPRICE FROM table2 GROUP BY ID, ITEM) AS 
T2
ON T1.ID = T2.id  AND T1.item = T2.item WHERE T1.SUMPRICE <> T2.SUMPRICE 

希望它有所帮助!

编辑1 如果您想获得所有不匹配的行,那就是:

  1. 表2中的行,其中id,item 价格与表1中的给定行不匹配
  2. 表2中的行,其中没有任何列与表1中的给定行同时匹配
  3. 您可以使用EXCEPT语句,例如:

    (SELECT ID, ITEM, SUM(PRICE) AS SUMPRICE FROM table2 GROUP BY ID, ITEM) 
     EXCEPT
    (SELECT ID, ITEM, SUM(PRICE) AS SUMPRICE FROM table1 GROUP BY ID, ITEM) 
    

    返回:

    ID   ITEM                 SUMPRICE
    ---- -------------------- -----------
    10   book                 50