如何在SQL Server查询中使用连接和sum()

时间:2015-02-13 10:27:37

标签: sql sql-server

我有两张表ItemsTransactions。在项目表中,列出了所有项目。在交易表中,特定员工可以根据他/她请求的数量请求项目。

如何使用联接来合并两个表中的数据,这两个表将计算每个项目的余额数量?

注意:(数量余额=数量 - TR_Qty)

ITEMS表:

  | ID |  ITEM   | UNIT | QUANTITY | PRICE  |
  | 1  | Perfume | btl. |   50     | 200.00 |
  | 2  | Battery | pc.  |  100     | 25.00  |
  | 3  | Milk    | can  |  250     | 70.00  |
  | 4  | Soap    | pack |  400     | 150.00 |

TRANSACTIONS表:

  | ID | ITEM_ID | TR_QTY   |  REQUSETOR  | PROCESSOR   |   Date     |Time |     
  | 1  |   1     |    20    | A. Jordan   | K. Koslav   | 12-22-2014 |09:00| 
  | 2  |   2     |     8    | B. Wilkins  | Z. Flores   | 12-22-2014 |10:03|
  | 3  |   3     |    80    | C. Potran   | A. Mabag    | 12-26-2014 |14:23|
  | 4  |   3     |    45    | D. Korvak   | D. Sanchez  | 12-28-2014 |15:33|
  | 5  |   4     |    22    | C. Carvicci | A. Flux     | 12-31-2014 |16:02|
  | 6  |   1     |    18    | F. Sansi    | N. Mahone   | 01-22-2015 |08:45|
  | 7  |   4     |    14    | Z. Gorai    | M. Sucre    | 01-30-2015 |16:33|
  | 8  |   2     |     7    | L. ZOnsey   | P. Panchito | 02-11-2015 |17:22|

期望的输出:

  | ID | ITEM    | QUANITY BALANCE|
  | 1  | Perfume |     462        |
  | 2  | Battery |     85         |
  | 3  | Milk    |     125        |
  | 4  |Soap     |     364        |

3 个答案:

答案 0 :(得分:0)

SELECT ITEM , ( SELECT (SUM(TRANSACTIONS.TR_QTY)-ITEMS.TR_QTY) FROM TRANSACTIONS WHERE TRANSACTIONS.ITEM_ID = ITEMS.ID ) AS QUANITY BALANCE FROM ITEMS 

字段名称和表名称与您在查询中提到的一样(您应该更改它,因为空格对字段或表名称无效)

答案 1 :(得分:0)

您可以通过使用外部应用并在其中创建数量总和来执行此操作:

select 
    I.ID,
    I.ITEM,
    I.QUANTITY - isnull(T.QUANTITY, 0) as BALANCE
from
    ITEMS I
    outer apply (
        select sum(TR_QTY) as QUANTITY
        from TRANSACTIONS T
        where T.ITEM_ID = I.ID
    ) T

答案 2 :(得分:0)

试试这个:

DECLARE @Items TABLE(ID INT, Item NVARCHAR(10), Q INT)
DECLARE @Transactions TABLE(ID INT, ItemID INT, TQ INT)

INSERT INTO @Items VALUES
(1, 'Perfume', 500),
(2, 'Battery', 100),
(3, 'Milk', 250),
(4, 'Soap', 400)


INSERT INTO @Transactions VALUES
(1, 1, 20),
(2, 2, 8),
(3, 3, 80),
(4, 3, 45),
(5, 4, 22),
(6, 1, 18),
(7, 4, 14),
(8, 2, 7)


SELECT i.ID, i.Item, MAX(i.Q) - ISNULL(SUM(t.TQ), 0) AS Balance 
FROM @Items i
LEFT JOIN @Transactions t ON t.ItemID = i.ID
GROUP BY i.ID, i.Item
ORDER BY i.ID

输出:

ID  Item    Balance
1   Perfume 462
2   Battery 85
3   Milk    125
4   Soap    364