T-SQL Query with joins, case when, grouping etc. HELP! :(

时间:2018-02-03 11:05:25

标签: sql-server tsql join ssms

((( disclaimer - I am sorry if I explained this in a difficult manner lol )))

Hello!

I've been wondering. So I have a query similar to this (i have simplified the data) -

SELECT S.StoreName, I.ItemName, T.CreditAmount, T.DebitAmount

FROM TransactionsTable T

LEFT JOIN ItemsTable I ON I.Id = T.ItemID

LEFT JOIN StoresTable S ON S.Id = T.StoreId

GROUP BY Store, Item, CreditAmount, DebitAmount

This is the result

Store Name| Item      | CreditAmount | DebitAmount
------------------------------------------------------------------
Store 1   | Bread     | 1000         |  0
Store 1   | Eggs      |  0           |  250
Store 1   | Bacon     |  0           |  310
Store 2   | Rice      | 700          |  0
Store 2   | Beans     | 135          |  0
Store 2   | Quinoa    | 111          |  0
Store 3   | Yam       | 0            |  120
Store 3   | Potatoes  | 0            |  120
Store 3   | Cocoyam   | 120          |  0

The result I want is

TransactionCategory | Items    | SumOfAllCreditsInTHisStore| SumOfAllDebitsInThisStore 
Store 1             | Bread    | 1000                      | 560
Store 1             | Eggs     | 1000                      | 560
Store 1             | Bacon    | 1000                      | 560
Store 2             | Rice     | 946                       | 0
Store 2             | Beans    | 946                       | 0
Store 2             | Quinoa   | 946                       | 0
Store 3             | Yam      | 120                       | 240
Store 3             | Potatoes | 120                       | 240
Store 3             | Cocoyam  | 120                       | 240

I need a query that brings out

  • (a) the store name
  • (b) the items sold in the store
  • (c) sum of all credits in the store regardless of the item
  • (d) sum of all debits in the store regardless of the item

Suggestions??

2 个答案:

答案 0 :(得分:1)

Solution will work for SQL Server 2012 and later versions:

SELECT DISTINCT 
       S.StoreName
     , I.ItemName
     , SUM(T.CreditAmount) OVER (PARTITION BY S.StoreName) AS SumOfAllCreditsInTHisStore
     , SUM(T.DebitAmount) OVER (PARTITION BY S.StoreName) AS SumOfAllDebitsInThisStore

FROM TransactionsTable T

LEFT JOIN ItemsTable I ON I.Id = T.ItemID

LEFT JOIN StoresTable S ON S.Id = T.StoreId

答案 1 :(得分:0)

SELECT S.StoreName AS TransactionCategory, I.ItemName AS Items , 
SUM (T.CreditAmount) OVER (PARTITION BY S.StoreName ORDER BY Item ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS SumOfAllCreditsInTHisStore, 
SUM (T.DebitAmount) OVER (PARTITION BY S.StoreName ORDER BY Item ROWS BETWEEN  UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS SumOfAllDebitsInThisStore
FROM TransactionsTable T
LEFT JOIN ItemsTable I ON I.Id = T.ItemID
LEFT JOIN StoresTable S ON S.Id = T.StoreId
GROUP BY S.StoreName, I.ItemName, T.CreditAmount, T.DebitAmount;