We had an issue with our stock whereby we had a balance column that would be added to or subtracted from whenever a transaction occurred.
There were some issues that we could not trace and hence have made changes whereby the stock would be calculated by adding and subtracting (where appropriate) the quantity moving and come up to today's stock value.
However now, the structure is such that one product has multiple stocks therefore product A with expiry 01/2012, 02/2013 etc.
I have currently created a query whereby for one stock of a product, it would calculate its current stock as follows:
select
(select ISNULL(sum(gd.qty),0) as grnadd from grns as g
INNER JOIN grndetails as gd ON g.id = gd.grnid
INNER JOIN stocks as s ON s.id = gd.stockid
where g.locationid = 10 and s.prodid =2653)
-
(select ISNULL(sum(cod.qty), 0) as salesub from salesorders as co
INNER JOIN salesorddetails as cod ON co.id = cod.cusordid
INNER JOIN stocks as s ON s.id = cod.stockid
where co.status != 'cancel' and co.locid = 10 and s.prodid =2653)
-
(select ISNULL(sum(cod.qty), 0) as cussub from customerorders as co
INNER JOIN customerorddetails as cod ON co.id = cod.cusordid
INNER JOIN stocks as s ON s.id = cod.stockid
where co.status != 'cancel' and co.locid = 10 and s.prodid =2653)
Therefore in this case the stock is calculated for one product however can I make a query that would list all products with their totals (as above) in the second column?
Thank you and hope the structure is understood from the above query
EDIT:
Stocks Table: id, prodid, expiry
Products Table: id, tradename
GRN Details Table: id, grnid, qty, stockid (since its affecting the stock not product)
Sales & Customer Order Details Table: id, cusordid, qty, stockid
GRN & Sales & Cus Ord Table: id, locid
Locations Table: id, locname
try to include all product-ids and group by it. here's some proposed code
select prodid, sum(total) as total from (
(select s.prodid
, ISNULL(sum(gd.qty),0) as total
from grns as g
INNER JOIN grndetails as gd
ON g.id = gd.grnid
INNER JOIN stocks as s
ON s.id = gd.stockid
where g.locationid = 10 group by s.prodid)
union all
(select s.prodid
, ISNULL(sum(cod.qty), 0)*(-1) as total
from salesorders as co
INNER JOIN salesorddetails as cod
ON co.id = cod.cusordid
INNER JOIN stocks as s
ON s.id = cod.stockid
where co.status != 'cancel'
and co.locid = 10 group by s.prodid)
union all
(select s.prod_id
, ISNULL(sum(cod.qty), 0)*(-1) as total
from customerorders as co
INNER JOIN customerorddetails as cod
ON co.id = cod.cusordid
INNER JOIN stocks as s
ON s.id = cod.stockid
where co.status != 'cancel'
and co.locid = 10 group by s.prodid)
) as x
group by prodid
i have changed all the minuses to union-alls so that the product-ids will not get subtracted from each other and the grand total will be calculated respective to your product-ids.
Try this:
WITH
S AS (
SELECT DISTINCT prodid FROM stocks
),
L AS (
/* SELECT 10 AS locationid */
SELECT DISTINCT locationid FROM grns
),
T1 AS (
select
g.locationid,
s.prodid,
sum(gd.qty) as grnadd
from grns as g
INNER JOIN grndetails as gd ON g.id = gd.grnid
INNER JOIN stocks as s ON s.id = gd.stockid
GROUP BY g.locationid, s.prodid
),
T2 AS (
select
co.locid as locationid,
s.prodid,
sum(cod.qty) as salesub
from salesorders as co
INNER JOIN salesorddetails as cod ON co.id = cod.cusordid
INNER JOIN stocks as s ON s.id = cod.stockid
where co.status != 'cancel'
GROUP BY co.locid, s.prodid
),
T3 AS (
select
co.locid as locationid,
s.prodid,
sum(cod.qty) as cussub
from customerorders as co
INNER JOIN customerorddetails as cod ON co.id = cod.cusordid
INNER JOIN stocks as s ON s.id = cod.stockid
where co.status != 'cancel'
GROUP BY co.locid, s.prodid
)
SELECT
S.prodid, L.locationid, ISNULL(grnadd, 0) - ISNULL(salesub, 0) - ISNULL(cussub, 0)
FROM
S CROSS JOIN
L LEFT OUTER JOIN
T1 ON T1.locationid = L.locationid AND T1.prodid = S.prodid LEFT OUTER JOIN
T2 ON T2.locationid = L.locationid AND T2.prodid = S.prodid LEFT OUTER JOIN
T3 ON T3.locationid = L.locationid AND T3.prodid = S.prodid
I assumed that location might be also important, so it returns 3 columns. If you want results only for location with id 10, then in L CTL uncomment first line and comment second.
assuming lots about your data model (hopefully i understood the question right), a group by might be the answer:
select
(select s.prodid, ISNULL(sum(gd.qty),0) as grnadd from grns as g
INNER JOIN grndetails as gd ON g.id = gd.grnid
INNER JOIN stocks as s ON s.id = gd.stockid
where g.locationid = 10
GROUP BY s.prodid)
-
(select s.prodid, ISNULL(sum(cod.qty), 0) as salesub from salesorders as co
INNER JOIN salesorddetails as cod ON co.id = cod.cusordid
INNER JOIN stocks as s ON s.id = cod.stockid
where co.status != 'cancel' and co.locid = 10
GROUP BY s.prodid)
-
(select s.prodid, ISNULL(sum(cod.qty), 0) as cussub from customerorders as co
INNER JOIN customerorddetails as cod ON co.id = cod.cusordid
INNER JOIN stocks as s ON s.id = cod.stockid
where co.status != 'cancel' and co.locid = 10
GROUP BY s.prodid)
Related
I'm trying to get a report for figures from multiple transaction tables. Each table has a foreign key that is a lookup for the day it was taken on, and what location it was taken at called Site_Lookup_Id. It's giving me figures that are much larger than they should be.
#Site_Lookup_Ids dbo.Id_List READONLY
SELECT SL.Site_Lookup_Id, D.[Start],SUM(I.Amount) AS Income,
SUM(P.Amount) AS Payouts,SUM(DP.Amount) AS Deposit
FROM CashUp_Site_Lookup SL
INNER JOIN #Site_Lookup_Ids IDs ON Ids.Id = SL.Site_Lookup_Id
INNER JOIN CashUp_Day D ON SL.Day_Id = D.Day_Id
LEFT JOIN CashUp_Deposit DP ON DP.Redeemed_Site_Lookup_Id = SL.Site_Lookup_Id
AND DP.No_Show != 1
LEFT JOIN CashUp_Income I ON I.Site_Lookup_Id = SL.Site_Lookup_Id
LEFT JOIN CashUp_Payout P ON P.Site_Lookup_Id = SL.Site_Lookup_Id
GROUP BY SL.Site_Lookup_Id, D.[Start]
Not all sums will have a value as some days no transactions for a given table will be taken on the day - In this the value should be zero.
The issue is that running this gives me crazy high values - £7500 for income against one day, when if I do a simple check it's £40 for that day like so.
SELECT SUM(Amount) FROM Cashup_Income WHERE Site_Lookup_Id IN (values...)
Maybe something like...
It really depends on the relationships and when you want the values to be summed.
SELECT SL.Site_Lookup_Id
, D.[Start]
, SUM(I.Amount) over (partition by Key of I table) AS Income
, SUM(P.Amount) over (partition by Key of P table) AS Payouts
, SUM(DP.Amount) over (partition by Key of DP Table) AS Deposit
FROM CashUp_Site_Lookup SL
INNER JOIN #Site_Lookup_Ids IDs ON Ids.Id = SL.Site_Lookup_Id
INNER JOIN CashUp_Day D ON SL.Day_Id = D.Day_Id
LEFT JOIN CashUp_Deposit DP ON DP.Redeemed_Site_Lookup_Id = SL.Site_Lookup_Id
AND DP.No_Show != 1
LEFT JOIN CashUp_Income I ON I.Site_Lookup_Id = SL.Site_Lookup_Id
LEFT JOIN CashUp_Payout P ON P.Site_Lookup_Id = SL.Site_Lookup_Id
GROUP BY SL.Site_Lookup_Id, D.[Start]
The problem stems from the fact that your tables are 1:M Causing values to repeat. These repeated values are then getting added to your sum. The joins cause this issue. So I think you can sum using a partition to eliminate the duplicates or:
Use derived tables or a CTE and sum the values BEFORE you join.
Using CTE's (Common Table Expressions)
WITH DP AS (SELECT sum(Amount) As Deposit
, Redeemed_Site_Lookup_ID
FROM CashUp_Deposit
WHERE No_Show !=1
GROUP BY Redeemed_Site_Lookup_ID),
I AS (SELECT sum(Amount) as Income
, Site_Lookup_Id
FROM CashUp_Income
GROUP BY Site_Lookup_Id),
P AS (SELECT sum(Amount) as Payouts
, Site_Lookup_Id
FROM CashUp_Payout
GROUP BY Site_Lookup_Id)
SELECT SL.Site_Lookup_Id
, D.[Start]
, Income
, Payouts
, Deposit
FROM CashUp_Site_Lookup SL
INNER JOIN #Site_Lookup_Ids IDs
ON Ids.Id = SL.Site_Lookup_Id
INNER JOIN CashUp_Day D
ON SL.Day_Id = D.Day_Id
LEFT JOIN DP
ON DP.Redeemed_Site_Lookup_Id = SL.Site_Lookup_Id
LEFT JOIN I
ON I.Site_Lookup_Id = SL.Site_Lookup_Id
LEFT JOIN P
ON P.Site_Lookup_Id = SL.Site_Lookup_Id
Presumably, you are generating a Cartesian product with your joins. Because you have no filtering, do the aggregation before the joins:
LEFT JOIN
(SELECT DP.Redeemed_Site_Lookup_Id, SUM(DP.Amount) AS Deposit
FROM CashUp_Deposit DP
WHERE DP.No_Show != 1
GROUP BY DP.Redeemed_Site_Lookup_Id
) DP
ON DP.Redeemed_Site_Lookup_Id = SL.Site_Lookup_Id LEFT JOIN
(SELECT I.Site_Lookup_Id, SUM(I.Amount) AS Income
FROM CashUp_Income I
GROUP BY I.Site_Lookup_Id
) I
ON I.Site_Lookup_Id = SL.Site_Lookup_Id LEFT JOIN
(SELECT P.Site_Lookup_Id, SUM(P.Amount) AS Payout
FROM CashUp_Payout P
GROUP BY I.Site_Lookup_Id
) P
ON P.Site_Lookup_Id = SL.Site_Lookup_Id
Then adjust the rest of your query to remove the GROUP BY and SUM()s.
I'm working on another SQL query, trying to group a collection of records while doing a count and joining tables. See below for goal, current query, and attached scripts for building and populating tables.
Show all customers who have checked more books than DVDs. Display
customer name, total book checkouts and total DVD checkouts. Sort
results by customer first name and last name.
SELECT C.CUSTOMER_FIRSTNAME, C.CUSTOMER_LASTNAME, COUNT(T.TRANSACTION_ID)
FROM customer C
INNER JOIN library_card LC ON C.CUSTOMER_ID = LC.CUSTOMER_ID
INNER JOIN transaction T ON LC.LIBRARY_CARD_ID = T.LIBRARY_CARD_ID
INNER JOIN physical_item P ON T.PHYSICAL_ITEM_ID = P.PHYSICAL_ITEM_ID
INNER JOIN catalog_item CT ON P.CATALOG_ITEM_ID = CT.CATALOG_ITEM_ID
GROUP BY C.CUSTOMER_FIRSTNAME, C.CUSTOMER_LASTNAME
ORDER BY C.CUSTOMER_FIRSTNAME, C.CUSTOMER_LASTNAME;
Run first: https://drive.google.com/open?id=1PYAZV4KIfZtxP4eQn35zsczySsxDM7ls
Run second: https://drive.google.com/open?id=1pAzWmJqvD3o3n6YJqVUM6TtxDafKGd3f
EDIT
With some help from Mr. Barbaros I've come up with the below query, which is closer. However, this query isn't returning any results for DVDs, which leads me to believe it's a join issue.
SELECT C.CUSTOMER_FIRSTNAME, C.CUSTOMER_LASTNAME, COUNT(CT1.TYPE) AS BOOK_COUNT, COUNT(CT2.TYPE) AS DVD_COUNT
FROM customer C
INNER JOIN library_card LC ON C.CUSTOMER_ID = LC.CUSTOMER_ID
INNER JOIN transaction T ON LC.LIBRARY_CARD_ID = T.LIBRARY_CARD_ID
INNER JOIN physical_item P ON T.PHYSICAL_ITEM_ID = P.PHYSICAL_ITEM_ID
INNER JOIN catalog_item CT1 ON P.CATALOG_ITEM_ID = CT1.CATALOG_ITEM_ID AND CT1.TYPE = 'BOOK'
LEFT OUTER JOIN catalog_item CT2 ON P.CATALOG_ITEM_ID = CT2.CATALOG_ITEM_ID AND CT2.TYPE = 'DVD'
GROUP BY C.CUSTOMER_FIRSTNAME, C.CUSTOMER_LASTNAME, CT1.TYPE, CT2.TYPE
ORDER BY C.CUSTOMER_FIRSTNAME, C.CUSTOMER_LASTNAME;
Use "conditional aggregates" (use a case expression inside the aggregate function)
SELECT
C.CUSTOMER_FIRSTNAME
, C.CUSTOMER_LASTNAME
, COUNT( CASE WHEN CT.TYPE = 'BOOK' THEN T.TRANSACTION_ID END ) books
, COUNT( CASE WHEN CT.TYPE = 'DVD' THEN T.TRANSACTION_ID END ) dvds
FROM customer C
INNER JOIN library_card LC ON C.CUSTOMER_ID = LC.CUSTOMER_ID
INNER JOIN transaction T ON LC.LIBRARY_CARD_ID = T.LIBRARY_CARD_ID
INNER JOIN physical_item P ON T.PHYSICAL_ITEM_ID = P.PHYSICAL_ITEM_ID
INNER JOIN catalog_item CT ON P.CATALOG_ITEM_ID = CT.CATALOG_ITEM_ID
GROUP BY
C.CUSTOMER_FIRSTNAME
, C.CUSTOMER_LASTNAME
HAVING
COUNT( CASE WHEN CT.TYPE = 'BOOK' THEN T.TRANSACTION_ID END )
> COUNT( CASE WHEN CT.TYPE = 'DVD' THEN T.TRANSACTION_ID END )
ORDER BY
C.CUSTOMER_FIRSTNAME
, C.CUSTOMER_LASTNAME
;
You can use catalog_item table twice( think of as seperate tables for books and dvds ), and compare by HAVING clause as :
SELECT C.CUSTOMER_FIRSTNAME, C.CUSTOMER_LASTNAME,
COUNT(CT1.CATALOG_ITEM_ID) as "Book Checkout",
COUNT(CT2.CATALOG_ITEM_ID) as "DVD Checkout"
FROM customer C
INNER JOIN library_card LC ON C.CUSTOMER_ID = LC.CUSTOMER_ID
INNER JOIN transaction T ON LC.LIBRARY_CARD_ID = T.LIBRARY_CARD_ID
INNER JOIN physical_item P ON T.PHYSICAL_ITEM_ID = P.PHYSICAL_ITEM_ID
LEFT JOIN catalog_item CT1 ON P.CATALOG_ITEM_ID = CT1.CATALOG_ITEM_ID AND CT1.TYPE = 'BOOK'
LEFT JOIN catalog_item CT2 ON P.CATALOG_ITEM_ID = CT2.CATALOG_ITEM_ID AND CT1.TYPE = 'DVD'
GROUP BY C.CUSTOMER_FIRSTNAME, C.CUSTOMER_LASTNAME
HAVING COUNT(CT1.CATALOG_ITEM_ID) > COUNT(CT2.CATALOG_ITEM_ID)
ORDER BY C.CUSTOMER_FIRSTNAME, C.CUSTOMER_LASTNAME;
CUSTOMER_FIRSTNAME CUSTOMER_LASTNAME Book Checkout DVD Checkout
------------------ ----------------- ------------- -------------
Deena Pilgrim 3 1
Emile Cross 5 2
Please try to remove ,CT1.TYPE, CT2.TYPE on your group by clause.
I am running the following script but am encountering an error. It is essentially the combination of two separate scripts. So I think one of the JOINs is off but not sure where. I am pulling data from our ERP via an ODBC in winsql.
Also how would I add month to this? Probably something simple like:
TO_CHAR(Month(t.TRANDATE,'YYYY-MM-DD')) AS CreatedMonth
The query which has got problem is:
SELECT
t.TRANSACTION_TYPE AS TranType
,tl.ACCOUNT_ID AS AcctId
,a.NAME AS Account
,a.TYPE_NAME AS AcctType
,t.TRANSACTION_ID AS DCOGSTranId
,t.TRANID AS DCOGSNo
,TO_CHAR(t.TRANDATE,'YYYY-MM-DD') AS DCOGSCreateDt
,TO_CHAR(t.TRANDATE,'YYYY-MM-DD') AS CDate
,t.CREATED_BY_ID AS DCOGSCreatedById
,tl.SUBSIDIARY_ID AS SubSidId
,ss.NAME AS SubSidiary
,tl.LOCATION_ID AS LocId
,t.ENTITY_ID AS CustomerId
,tl.ITEM_ID AS ItemId
,NVL(SUM(tl.GROSS_AMOUNT),0) AS DirectCOGS$
,NVL(SUM(tl.ITEM_COUNT),0) AS DirectCOGSQty
,ilm.ITEM_ID AS ItemId
,ss.NAME AS SubSidiary
,ilm.LOCATION_ID AS LocId
,TO_CHAR(ed.ExpireDt,'YYYY-MM-DD') AS ExpireDt
,TO_CHAR(CURRENT_DATE,'YYYY-MM-DD') AS CDate
,NVL(ilm.AVERAGE_COST,0)*NVL(u.CONVERSION_RATE,1) AS AvgCost
,NVL(ilm.LAST_PURCHASE_PRICE,0)*NVL(u.CONVERSION_RATE,1) AS LastPurchPrice
,NVL(ilm.AVERAGE_COST,0) * NVL(ilm.ON_HAND_COUNT,0) AS OnHandCost$
,NVL(ilm.ON_HAND_COUNT,0) / NVL(u.CONVERSION_RATE,1) AS OnHandQty
,NVL(bin.BinOnHandQty,0) / NVL(u.CONVERSION_RATE,1) AS BinOnHandQty
,NVL(ilm.AVERAGE_COST,0) * (NVL(ilm.IN_TRANSIT_COUNT,0)) AS InTranCost$
,NVL(ilm.IN_TRANSIT_COUNT,0) / NVL(u.CONVERSION_RATE,1) AS InTranQty
,NVL(ilm.AVERAGE_COST,0) * (NVL(ilm.AVAILABLE_COUNT,0)) AS AvailCost$
,NVL(ilm.AVAILABLE_COUNT,0) / NVL(u.CONVERSION_RATE,1) AS AvailQty
,NVL(bin.BinAvailQty,0) / NVL(u.CONVERSION_RATE,1) AS BinAvailQty
,NVL(ilm.AVERAGE_COST,0) * (NVL(ilm.ON_ORDER_COUNT,0)) AS OnOrderCost$
,NVL(ilm.ON_ORDER_COUNT,0) / NVL(u.CONVERSION_RATE,1) AS OnOrderQty
,NVL(ilm.AVERAGE_COST,0) * (NVL(ilm.QUANTITYBACKORDERED,0)) AS BackOrdrdCost$
,NVL(ilm.QUANTITYBACKORDERED,0) / NVL(u.CONVERSION_RATE,1) AS BackOrdrdQty
FROM TRANSACTIONS t
JOIN TRANSACTION_LINES tl ON t.TRANSACTION_ID = tl.TRANSACTION_ID
LEFT JOIN ITEMS i ON tl.ITEM_ID = i.ITEM_ID
LEFT JOIN TRANSACTIONS t2 ON t.CREATED_FROM_ID = t2.TRANSACTION_ID
LEFT JOIN ACCOUNTS a ON tl.ACCOUNT_ID = a.ACCOUNT_ID
LEFT JOIN SUBSIDIARIES ss ON tl.SUBSIDIARY_ID = ss.SUBSIDIARY_ID
WHERE tl.ACCOUNT_ID = 128
FULL OUTER JOIN ITEM_LOCATION_MAP ilm ON tl.ITEM_ID = ilm.ITEM_ID
JOIN ITEMS i ON ilm.ITEM_ID = i.ITEM_ID
LEFT JOIN UOM u ON i.PURCHASE_UNIT_ID = u.UOM_ID
LEFT JOIN PRIMARY_SUBSIDIARYS_MAP psm ON ilm.ITEM_ID = psm.ITEM_ID
LEFT JOIN SUBSIDIARIES ss ON psm.SUBSIDIARY_ID = ss.SUBSIDIARY_ID
LEFT JOIN (
SELECT ITEM_ID, LOCATION_ID, MIN(EXPIRATION_DATE) AS ExpireDt FROM INVENTORY_NUMBER
WHERE EXPIRATION_DATE IS NOT NULL
GROUP BY ITEM_ID, LOCATION_ID) ed ON ilm.ITEM_ID = ed.ITEM_ID AND
ilm.LOCATION_ID = ed.LOCATION_ID
LEFT JOIN (
SELECT ITEM_ID, LOCATION_ID, SUM(ON_HAND_COUNT) AS BinOnHandQty,
SUM(AVAILABLE_COUNT) AS BinAvailQty
FROM BIN_NUMBER_COUNTS
GROUP BY ITEM_ID, LOCATION_ID) bin ON ilm.ITEM_ID = bin.ITEM_ID AND
ilm.LOCATION_ID = bin.LOCATION_ID
WHERE (ilm.ON_HAND_COUNT != 0 OR ilm.IN_TRANSIT_COUNT != 0 OR
ilm.ON_ORDER_COUNT != 0 OR ilm.QUANTITYBACKORDERED != 0)
GROUP BY
t.TRANSACTION_TYPE
,tl.ACCOUNT_ID
,a.NAME
,a.TYPE_NAME
,t.TRANSACTION_ID
,t.TRANID
,t.TRANDATE
,t.CREATED_BY_ID
,tl.SUBSIDIARY_ID
,ss.NAME
,tl.LOCATION_ID
,t.ENTITY_ID
,tl.ITEM_ID
Really should post what the error is to help us out...but
LEFT JOIN SUBSIDIARIES ss ON tl.SUBSIDIARY_ID = ss.SUBSIDIARY_ID
WHERE tl.ACCOUNT_ID = 128
FULL OUTER JOIN ITEM_LOCATION_MAP ilm ON tl.ITEM_ID = ilm.ITEM_ID
Replace WHERE with AND.
where is a separate clause and not part of the join statement. you can use and key1 = key 1 and key 2 = key 2 and key 3 = 'hi'
Here's the Query
SELECT
MAX (Supplier.SupplierName) as Supplier,
MAX (Department.Name) as Department,
MAX (Category.Name) as Category,
MAX (ItemClass.ItemLookupCode) as Matrix,
MAX (Item.ItemLookupCode) as ItemLookupCode,
MAX (Item.Description) as Description,
SUM (TransactionEntry.Quantity) as QtySold,
MAX (Item.Cost) as Cost,
MAX (Item.Price) as Price,
MAX (TransactionEntry.Price) as SoldPrice,
SUM (TransactionEntry.Price * TransactionEntry.Quantity) as TotalSale,
MAX (Item.Quantity) as OnHand
FROM TransactionEntry
INNER JOIN [Transaction] WITH(NOLOCK)
ON TransactionEntry.TransactionNumber = [Transaction].TransactionNumber AND TransactionENtry.ItemType <> 9 AND TransactionEntry.StoreID = [Transaction].StoreID
INNER JOIN Batch WITH(NOLOCK)
ON [Transaction].BatchNumber = Batch.BatchNumber AND [Transaction].StoreID = Batch.StoreID
LEFT JOIN Item WITH(NOLOCK)
ON TransactionEntry.ItemID = Item.ID
LEFT JOIN Department WITH(NOLOCK)
ON Item.DepartmentID = Department.ID
LEFT JOIN Category WITH(NOLOCK)
ON Item.CategoryID = Category.ID
LEFT JOIN Supplier WITH(NOLOCK)
ON Item.SupplierID = Supplier.ID
LEFT JOIN ReasonCode AS ReasonCodeDiscount WITH(NOLOCK)
ON TransactionEntry.DiscountReasonCodeID = ReasonCodeDiscount.ID
LEFT JOIN ReasonCode AS ReasonCodeTaxChange WITH(NOLOCK)
ON TransactionEntry.TaxChangeReasonCodeID = ReasonCodeTaxChange.ID
LEFT JOIN ReasonCode AS ReasonCodeReturn WITH(NOLOCK)
ON TransactionEntry.ReturnReasonCodeID = ReasonCodeReturn.ID
LEFT JOIN Store ON [Transaction].StoreID = Store.ID
LEFT JOIN ItemClassComponent WITH(NOLOCK)
ON Item.ID = ItemClassComponent.ItemID
LEFT JOIN ItemClass WITH(NOLOCK)
ON ItemClassComponent.ItemClassID = ItemClass.ID
WHERE DATEDIFF(week, [Transaction].Time, GETDATE()) = 1 AND
Supplier.SupplierName = 'Name'
GROUP BY Item.ItemLookupCode
Here's the query and how do I add summary row for total numbers for some of the column? I tried several things but could not find anything...
Please help!!!!
http://i29.photobucket.com/albums/c259/xkrntamax/Capture_zps511d8kun.jpg
You are probably looking for grouping sets or with rollup:
Change the group by clause to:
GROUP BY GROUPING SETS ((Item.ItemLookupCode), ())
How can I Count the Lending comments for each lending (the comments is on another table called "LendingComments" with a reference Column called "LendingId" ?
SELECT LendingStatus.Status, Products.Productname, Products.Serial_number, Deposits.Amount, Lendings.DeliveryDate, Lendings.Id AS LendingId, Products.Id AS ProductId FROM Lendings
LEFT JOIN Products ON Lendings.ProductId = Products.Id
LEFT JOIN LendingStatus ON Lendings.StatusId = LendingStatus.Id
LEFT JOIN Deposits ON Lendings.DepositId = Deposits.Id
WHERE PersonId = 561 ORDER BY DeliveryDate DESC
Maby like this (if I understand the question well enough)
SELECT
LendingStatus.Status, Products.Productname, Products.Serial_number,Deposits.Amount, Lendings.DeliveryDate, Lendings.Id AS LendingId, Products.Id AS ProductId, LendingComments.NumLendingComments
FROM Lendings
LEFT JOIN Products ON Lendings.ProductId = Products.Id
LEFT JOIN LendingStatus ON Lendings.StatusId = LendingStatus.Id
LEFT JOIN Deposits ON Lendings.DepositId = Deposits.Id
OUTER APPLY
(
SELECT
COUNT(*) AS NumLendingComments
FROM
LendingComments PL
WHERE
PL.LendingID = Lendings.LendingID
) AS LendingComments WHERE Personid = 561 ORDER BY DeliveryDate desc
Maybe this helps:
SELECT CommentCount = Sum(lc.comments)
OVER (
partition BY lc.id),
lendingstatus.status,
products.productname,
products.serial_number,
deposits.amount,
lendings.deliverydate,
lendings.id AS LendingId,
products.id AS ProductId
FROM lendings
LEFT JOIN products
ON lendings.productid = products.id
LEFT JOIN lendingstatus
ON lendings.statusid = lendingstatus.id
LEFT JOIN deposits
ON lendings.depositid = deposits.id
LEFT JOIN LendingComments lc
ON lc.LendingId = lendings.Lendings.Id
WHERE personid = 561
ORDER BY deliverydate DESC
However, you have not shown the PersonLendings table, have you?
Try this one -
SELECT ls.status
, p.Productname
, p.Serial_number
, d.AMOUNT
, l.DeliveryDate
, l.Id AS LendingId
, p.Id AS ProductId
, pl.cnt
FROM dbo.Lendings l
LEFT JOIN (
SELECT pl.LendingId, cnt = COUNT(pl.LendingComments)
FROM dbo.PersonLendings pl
GROUP BY pl.LendingId
) pl ON pl.LendingId = l.LendingId
LEFT JOIN dbo.Products p ON l.ProductId = p.Id
LEFT JOIN dbo.LendingStatus ls ON l.StatusId = ls.Id
LEFT JOIN dbo.Deposits d ON l.DepositId = d.Id
WHERE PersonID = 561
ORDER BY l.DeliveryDate DESC