TSQL: Join tables based on criteria - sql

The resultset I am aiming to receive is this:
My table structure is like:
The INVOICE table has INVTYPE column which defines whether the invoice is a sales invoice or a purchase invoice by holding 101 for sale and 201 for purchase.
My query will use a where statement to also filter down the STOCK table to a particular STOCKCODE.
I am trying to filter out products (STOCK) with a STOCKCODE = "XYZ"
If I run
SELECT *
FROM STOCK
WHERE STOCKCODE = 'XYZ'
I get 152 results. So I have 152 products with a STOCKCODE of 'XYZ' for sure..
My problem is when I try to join these tables. For simplicity, I have only tried to get INVTYPE 101 to keep it simple but my desired outcome is still with the 201.
I have tried joins and subqueries such as:
SELECT
S.STOCKNO, S.STOCKNAME, ISNULL(SUM(IIT.QTYSOLD), 0) AS QTY,
ISNULL(SUM(IIT.TOTAL), 0) AS TOTAL
FROM
STOCK S
LEFT JOIN
INVOICE_ITEM IIT ON S.STOCKID = IIT.STOCKID
LEFT JOIN
INVOICE INV ON IIT.INVID = INV.INVID
WHERE
S.STOCKCODE = 'XYZ' AND INV.TRANSTYPE = 101
GROUP BY
S.STOCKNO, S.STOCKNAME
This query returns 122 results. So I know that there are 30 items in the stock table that have not been sold, which I need to show them in the resultset with 0 (zero) in the relevant columns.
I also tried this:
SELECT
S.STOCKNO, S.STOCKNAME,
(SELECT ISNULL(SUM(TOTAL), 0)
FROM INVOICE_ITEM IIT
WHERE IIT.STOCKID = S.STOCKID) AS TOTAL,
(SELECT ISNULL(SUM(QTYSOLD), 0)
FROM INVOICE_ITEM IIT
WHERE IIT.STOCKID = S.STOCKID) AS QTY
FROM
STOCK S
WHERE
S.STOCKCODE = 'XYZ'
This query return the full 152 results because I did not filter by INVTYPE it returned the items which were purchased as well.
I am using SQL Server 2014
So my question is how can I achieve my desired resultset? and what am I doing wrong with my joins?
Thanks

You need a conditional aggregation
SELECT S.STOCKNO,
S.STOCKNAME,
ISNULL(SUM(CASE WHEN INV.TRANSTYPE = 201 THEN IIT.TOTAL END), 0) AS TOTAL_PURCHASED,
ISNULL(SUM(CASE WHEN INV.TRANSTYPE = 101 THEN IIT.TOTAL END), 0) AS TOTAL_SOLD,
ISNULL(SUM(CASE WHEN INV.TRANSTYPE = 201 THEN IIT.QTYSOLD END),0) AS QTY_PURCHASED,
ISNULL(SUM(CASE WHEN INV.TRANSTYPE = 101 THEN IIT.QTYSOLD END),0) AS QTY_SOLD
FROM STOCK S
LEFT JOIN INVOICE_ITEM IIT ON S.STOCKID = IIT.STOCKID
LEFT JOIN INVOICE INV ON IIT.INVID= INV.INVID
WHERE S.STOCKCODE= 'XYZ'
GROUP BY S.STOCKNO, S.STOCKNAME

since you are not joining your inner tables (INVOICE_ITEM) with their primary key this is an expected behavior.
you either need to use INVITEMID column for your join, you need to add STOCKID and INVID together.
SELECT ISNULL(SUM(TOTAL),0) FROM INVOICE_ITEM IIT
WHERE IIT.STOCKID = S.STOCKID and IIT.INVID = INV.INVID

For performance, it is tempting to try:
select s.stockno, s.stockname,
coalesce(i.total_purchased, 0) as total_purchased,
coalesce(i.total_sold, 0) as total_sold,
coalesce(i.qty_purchased, 0) as qty_purchased,
coalesce(i.qty_sold, 0) as qty_sold
from stock s outer apply
(select sum(case when i.transtype = 201 then ii.total end) as total_purchased,
sum(case when i.transtype = 101 then ii.total end) as total_sold,
sum(case when i.transtype = 201 then ii.qtysold end) as qty_purchased,
sum(case when i.transtype = 101 then ii.qtysold end) as qty_sold
from invoice_item ii join
invoice i
on ii.invid = i.invid
where s.stockid = ii.stockid
) i
where stockcode = 'XYZ'

Related

How to get multiple counts in one sql query across multiple tables

I have 2 tables
Company & products
I need to get 2 counts. One is the total count of products and the secondly count of products for sale_flg=1
This SQL does not seem to work..Tried several other ways..not able to get the expected results
SELECT A.COMPANY_NAME, COUNT(B.PRODUCT_ID) AS TOTAL_COUNT_OF_PRODUCTS,
(CASE WHEN B.SALEFLG =1 THEN 1 END) AS COUNT_OF_SALES
FROM COMPANY A LEFT JOIN
PRODUCT B
ON B.COMPANY_ID = A.COMPANY_ID
GROUP BY A.COMPANY_NAME
I think you just need a sum for the case:
SELECT C.COMPANY_NAME, COUNT(P.PRODUCT_ID) AS TOTAL_COUNT_OF_PRODUCTS,
SUM(CASE WHEN P.SALEFLG = 1 THEN 1 ELSE 0 END) AS COUNT_OF_SALES
FROM COMPANY C LEFT JOIN
PRODUCT P
ON P.COMPANY_ID = C.COMPANY_ID
GROUP BY C.COMPANY_NAME ;
If you have B.SALEFLG = 1 or 0 for you may try
Sum(B.SALEFLG) AS COUNT_OF_SALES
Or use UNION
If you use count then in else you should consider null because null is not consider in count aggregation and if you have B.SALEFLG =1 or 0 then use sum aggregation.
You can try below code:
SELECT A.COMPANY_NAME, COUNT(B.PRODUCT_ID) AS TOTAL_COUNT_OF_PRODUCTS,
count(CASE WHEN B.SALEFLG =1 THEN 1 else null END) AS COUNT_OF_SALES
FROM COMPANY A LEFT JOIN
PRODUCT B
ON B.COMPANY_ID = A.COMPANY_ID
GROUP BY A.COMPANY_NAME
OR try this:
SELECT A.COMPANY_NAME, COUNT(B.PRODUCT_ID) AS TOTAL_COUNT_OF_PRODUCTS,
sum(B.SALEFLG) AS COUNT_OF_SALES
FROM COMPANY A LEFT JOIN
PRODUCT B
ON B.COMPANY_ID = A.COMPANY_ID
GROUP BY A.COMPANY_NAME
This SQL server query is working.
Company Table and Product Table
Company Table CompanyID is join with Product table and sales_flg add in product table .
sales_flg = 1 record display in CntSalesflg
select Comp.CompID as CompID, COUNT(Pro.ProductID) as CntProdustID,
SUM(CASE WHEN Pro.SalesflagID = 1 THEN 1 ELSE 0 END) as CntSalesflg
from Product as Pro
inner join Company as Comp on Pro.CompID = Comp.CompID
GROUP by Comp.CompID

How to apply WHERE clause to multiple SELECT statements in SQL Server

I am creating an query that selects data from multiple tables. I have completed all the query but now I have to apply the WHERE clause to the whole query.
I have 9 select statements, and these are working fine. Data is being selected from different tables. Now I want to declare date session and I want all data to be filtered according to the date provided. I am using the below query:
SELECT
(SELECT COUNT(DISTINCT OrderItems.ProductID)
FROM OrderItems) AS 'TotalSoldItemsDistinct',
(SELECT COUNT(OrderItems.ProductID)
FROM OrderItems) AS 'TotalSoldItemsInDistinct',
(SELECT COUNT(Orders.OrderID)
FROM Orders) AS 'TotalOrders',
(SELECT COUNT(Orders.OrderID)
FROM Orders
WHERE Orders.OrderStatusID = #CompleteOStatusID) AS 'CompleteOrders',
(SELECT COUNT(Orders.OrderID)
FROM Orders
WHERE Orders.OrderStatusID = #PendingOStatusID) AS 'PendingOrders',
(SELECT COUNT(Orders.ClientID)
FROM Orders
WHERE Orders.ClientID != #WalkingCustID) AS 'namedcustomers',
(SELECT COUNT(Orders.ClientID)
FROM Orders
WHERE Orders.ClientID = #WalkingCustID) AS 'WalkingCustomers',
(SELECT SUM(OrderItems.PurchasePrice)
FROM OrderItems) AS 'TotalPurchasePrice',
(SELECT SUM(OrderItems.SalePrice)
FROM OrderItems) AS 'TotalSalePrice'
I am selecting data from 2 tables named 'Orders' and 'OrderItems', I have column TransactionDate in 'Orders' table and column OrderDate in OrderItems table on that I want to use where filter. Can anybody please suggest how to apply filter to whole query?
You could try this
;with tempOrderItems AS
(
SELECT
COUNT(DISTINCT OrderItems.ProductID) AS 'TotalSoldItemsDistinct',
COUNT(OrderItems.ProductID) AS 'TotalSoldItemsInDistinct',
SUM(OrderItems.PurchasePrice) AS 'TotalPurchasePrice',
SUM(OrderItems.SalePrice) AS 'TotalSalePrice'
FROM OrderItems ori
WHERE OrderDate BETWEEN xxx AND yyy
)
, tempOrders AS
(
SELECT
COUNT(o.OrderID) AS 'TotalOrders',
SUM(CASE WHEN o.OrderStatusID = #CompleteOStatusID THEN 1 ELSE 0 END) AS 'CompleteOrders',
SUM(CASE WHEN o.OrderStatusID = #PendingOStatusID THEN 1 ELSE 0 END) AS 'PendingOrders',
SUM(CASE WHEN o.ClientID != #WalkingCustID THEN 1 ELSE 0 END) AS 'namedcustomers',
SUM(CASE WHEN o.ClientID = #WalkingCustID THEN 1 ELSE 0 END) AS 'WalkingCustomers'
FROM Orders o
WHERE TransactionDate BETWEEN xxx AND yyy
)
SELECT * FROM tempOrderItems
CROSS JOIN tempOrders
It is not fully clear what you want as a result, but here 2 approaches.
Try the following for selecting data from 2 tables at the same time (replace the date with your criteria):
SELECT * FROM Orders AS o INNER JOIN OrderItems AS i WHERE o.TransactionDate = '2015-02-12' AND i.OrderDate = '2015-02-12';
The SELECT * selects all columns from both tables as a result and the WHERE ... AND ...-clause filters for results only with your defined date.
Try the following for selecting order item data only for Data that matches the date on a specific order.
SELECT i.* FROM Orders AS o INNER JOIN OrderItems AS i WHERE o.TransactionDate = i.OrderDate AND o.OrderID = '12345';
The SELECT i.* tells the query to only return the columns of the OrderItems. And the WHERE o.TransactionDate = i.OrderDate ensures that only order items from the same date of the order with the OrderID "12345" are returned (which is defined with the AND o.OrderID = '12345'. This would work given you have a field "OrderID" on your Order table and you want to use it as a criteria.

How to merge Two queries into one and result in one row

SELECT lp.lead_bucket_no ,
case when p.product = 'S-400' then qty end as 'S400' ,
case when p.product = 'Dish Antenna' then qty end as 'DishAntenna'
FROM lead_products lp INNER JOIN products p ON p.product_id = lp.product_id WHERE type = 'stock' GROUP BY lead_bucket_no ORDER BY lp.lead_bucket_no
and
SELECT lp.lead_bucket_no ,
case when p.product = 'S-400' then qty end as 'S400' ,
case when p.product = 'Dish Antenna' then qty end as 'DishAntenna'
FROM lead_products lp INNER JOIN products p ON p.product_id = lp.product_id WHERE type = 'order' GROUP BY lead_bucket_no ORDER BY lp.lead_bucket_no
how to merge these both query and and got record in single row. only type are different in both queries.
enter image description here
I think you just want OR (or IN) in the WHERE clause:
SELECT lp.lead_bucket_no,
SUM(case when p.product = 'S-400' then qty end) as S400,
SUM(case when p.product = 'Dish Antenna' then qty end) as DishAntenna
FROM lead_products lp INNER JOIN
products p
ON p.product_id = lp.product_id
WHERE type IN ('stock', 'order')
GROUP BY lead_bucket_no
ORDER BY lp.lead_bucket_no;
You also need some sort of aggregation for the expressions that are not in the GROUP BY clause. You may also want to aggregate by TYPE. It is unclear what you want for the final output.

SQL: How to create new columns depending on other column's value in the same table

I have 2 tables, Main and Units.
Main table:
Todate Unit CategoryID Quantity
1/7/2012 1 S 300
1/7/2012 1 U 350
2/7/2012 2 S 220
3/7/2012 2 S 50
3/7/2012 2 U 330
4/7/2012 1 S 200
4/7/2012 1 U 180
S = Sales, U = Upgrades
Units table:
UnitNum UnitName
1 Measures
2 Performance
I need to get this result:
Todate UnitNum UnitName Sales Upgrades
1/7/2012 1 Measures 300 350
2/7/2012 2 Performance 220
3/7/2012 2 Performance 50 330
4/7/2012 1 Measures 200 180
Meaning i need to create 2 columns - sales and upgrades, depending on the value in CategoryID, and i need them to be in the same row.
What i have so far is this
select Todate, Main.Unit, UnitName,
case when CategoryID = 'S' then Quantity end as Sales,
case when CategoryID = 'U' then Quantity end as Upgrades
from Main join Units on Main.UnitNum = Units.UnitNum
group by Todate, Main.Unit, UnitName
It gives me 2 new columns but they are in two separate rows..
I would really appreciate any help resolving this!
Thank you
You just need an aggregate query around the case statements.
select m.todate
, m.unit
, u.unitname
, sum(case when m.categoryid = 'S' then quantity end ) as sales
, sum(case when m.categoryid = 'U' then quantity end ) as upgrages
from main m
join units u
on m.unit = u.unitnum
group by m.todate, m.unit, u.unitname
You need something like this:
SELECT
Todate, m.Unit, UnitName,
Sales = (SELECT SUM(Quantity)
FROM dbo.Main m2
WHERE m.Todate = m2.Todate AND CategoryID = 'S'),
Updates = (SELECT SUM(Quantity)
FROM dbo.Main m2
WHERE m.Todate = m2.Todate AND CategoryID = 'U')
FROM
dbo.Main m
INNER join
dbo.Units u on m.Unit = u.UnitNum
GROUP BY
Todate, m.Unit, UnitName
ORDER BY
Todate, m.Unit, UnitName
This seems to be returning the output you're looking for:
You need to do a self-join of your main table with itself:
SELECT m1.todate, m1.unit AS unitnum, u.unitname,
SUM(m1.quantity) AS sales, SUM(m2.quantity) AS upgrades
FROM (SELECT todate, unit, quantity FROM Main WHERE category = 'S') AS m1
FULL OUTER JOIN
(SELECT todate, unit, quantity FROM Main WHERE category = 'U') AS m2
ON m1.todate = m2.todate AND m1.unit = m2.unit
JOIN units AS u
ON m1.unit = u.unitnum
GROUP BY m1.todate, m1.unit, u.unitname
ORDER BY m1.todate, m1.unit, u.unitname;
There are many other equivalent ways of writing the same query; this one preserves the symmetry of the problem fairly well, though. (Updated to use a FULL OUTER JOIN between the m1 and m2 sub-queries, to deal with cases where there are sales with no upgrades or upgrades with no sales.)
You could use PIVOT for this too:
WITH data AS (
SELECT
m.Todate,
m.UnitNum,
u.UnitName,
Category = CASE m.CategoryID
WHEN 'S' THEN 'Sales'
WHEN 'U' THEN 'Upgrades'
END,
Quantity
FROM Main m
INNER JOIN Units u
ON m.UnitNum = u.UnitNum
)
SELECT
Todate,
UnitNum,
UnitName,
Sales,
Upgrades
FROM data
PIVOT (
SUM(Quantity) FOR Category IN (Sales, Upgrades)
) p
;

How could I combine these 3 T-SQL statements into one?

I have 3 queries that I want to combine. 1 query is for total sales, 1 is for canceled orders, and 1 is for orders that don't include specific product types. Just need the total sales $$ to output in a table format as they are now. The only thing that changes between the 3 is the where statement. Thanks!
Edit: I realize I said "Just need the total sales $$" ... what I meant was I just need the sales $$ for each query in one table. So $x, $y, $z ... x is the total sales, y is the sales dollars that got cancelled, and z is the sales dollars for the specific items.
SELECT Sum((Items.Total+Items.Shipping)*OrderDetails.Quantity) AS Total
FROM Promo INNER JOIN (Orders INNER JOIN (Items INNER JOIN OrderDetails ON Items.ItemCode = OrderDetails.ItemCode) ON Orders.OrderNumber = OrderDetails.OrderNumber) ON Promo.Promo = Orders.Promo
WHERE ((Promo.OfferType)='Sale') AND ((Items.Date) Between '6/1/2010' And '12/31/2011');
SELECT Sum((Items.Total+Items.Shipping)*OrderDetails.Quantity) AS Canceled
FROM Promo INNER JOIN (Orders INNER JOIN (Items INNER JOIN OrderDetails ON Items.ItemCode = OrderDetails.ItemCode) ON Orders.OrderNumber = OrderDetails.OrderNumber) ON Promo.Promo = Orders.Promo
WHERE (((Promo.OfferType)='Sale') AND ((Items.Date) Between '6/1/2010' And '12/31/2011') AND ((Items.Status)="Canceled"));
SELECT Sum((Items.Total+Items.Shipping)*OrderDetails.Quantity) AS BadItems
FROM Promo INNER JOIN (Orders INNER JOIN (Items INNER JOIN OrderDetails ON Items.ItemCode = OrderDetails.ItemCode) ON Orders.OrderNumber = OrderDetails.OrderNumber) ON Promo.Promo = Orders.Promo
WHERE (((Promo.OfferType)='Sale') AND ((Items.Date) Between '6/1/2010' And '12/31/2011') AND ((Items.ProductType)<>2) AND ((Items.ProductType)<>6));
Thanks!
If you want the results on 1 row:
SELECT Total, Canceled, BadItems
FROM Query1, Query2, Query3
And if you want the results in 1 column, use a UNION:
Query1
UNION
Query2
UNION
Query3
Updated to reflect question clarification:
SELECT Sum(CASE WHEN Items.Status <> 'Canceled' AND Items.ProductType = 4 THEN (Items.Total+Items.Shipping)*OrderDetails.Quantity ELSE 0 END) AS Total ,
Sum(CASE WHEN Items.Status = 'Canceled' AND Items.ProductType = 4 THEN (Items.Total+Items.Shipping)*OrderDetails.Quantity ELSE 0 END) AS Canceled,
Sum(CASE WHEN Items.ProductType <> 4 THEN (Items.Total+Items.Shipping)*OrderDetails.Quantity ELSE 0 END) AS BadItems,
FROM Promo INNER JOIN (Orders INNER JOIN (Items INNER JOIN OrderDetails ON Items.ItemCode = OrderDetails.ItemCode) ON Orders.OrderNumber = OrderDetails.OrderNumber) ON Promo.Promo = Orders.Promo
WHERE ((Promo.OfferType)='Sale') AND ((Items.Date) Between '9/1/2010' And '12/31/2010');
try to use a procedure which will accept three values as input which will suite your were statements and it will give results in one table as want. if you are stuck let me know , i will help.