I am trying to obtain two different counts in a query. One count would be the count of the specific item in one table, and the other count would be the same but from a different table. I can write 2 different queries that provides me the info but in two different tables. I would like to write one query that puts it all into one table. Thank you guys for any of suggestions.
EDIT: To clarify, I would like to add the count from the second query to a column on the first query.
My query
select d.description, count(item_id) from productdetails pd
join inventory i on i.itemnum=pd.item_id
join departments d on d.dept_id=i.dept_id
where i.last_sold is not null and in_stock !=0
group by d.description
select d.description, count(itemnum)
from inventory i
join departments d on d.dept_id=i.dept_id
where in_stock != 0 and last_sold is not null
group by d.description
Place your queries in a sub-query where each count has been established and the "missing" count is assigned a value of zero.
Next, sum the count.
SELECT smmry.description
, SUM(smmry.pd_item_cnt) pd_item_cnt
, SUM(smmry.itemnum_cnt) itemnum_cnt
FROM (
SELECT d.description
, COUNT(pd.item_id) pd_item_cnt
, 0 itemnum_cnt
FROM productdetails pd
JOIN inventory i
ON i.itemnum = pd.item_id
JOIN departments d
ON d.dept_id = i.dept_id
WHERE i.last_sold IS NOT NULL
AND in_stock != 0
GROUP BY d.description
UNION ALL
SELECT d.description
, 0 pd_item_cnt
, COUNT(i.itemnum) itemnum_cnt
FROM inventory i
JOIN departments d
ON d.dept_id = i.dept_id
WHERE in_stock != 0
AND last_sold IS NOT NULL
GROUP BY d.description
) smmry
GROUP BY smmry.description
WITH Query1 (Description1, Count1) AS (
select d.description, count(item_id) from productdetails pd
join inventory i on i.itemnum=pd.item_id
join departments d on d.dept_id=i.dept_id
where i.last_sold is not null and in_stock !=0
group by d.description
),
Query2 (Description2, Count2) AS (
select d.description, count(itemnum)
from inventory i
join departments d on d.dept_id=i.dept_id
where in_stock != 0 and last_sold is not null
group by d.description
)
SELECT Description1, Count1, Description2, Count2 FROM Query1, Query2
Related
SELECT id,
login_id,
count,
case when count = 0 then 'Cat_A'
WHEN count between 1 and 10 then 'Cat_B'
WHEN count > 10 then 'Cat_C'
WHEN count IS NULL THEN 'Cat D'
END as Category
FROM
(
select id,login_id,min(ord_count) AS count
FROM table_1 X
JOIN table_2 Y
ON X.id_col = Y.id_col
WHERE date = '2022-02-02'
AND login_id = 'True'
group by id,login_id
)A
LEFT JOIN
(
SELECT id,COUNT(X.ord_no) AS count_of_orders
FROM table_1 X
WHERE X.date = '2022-02-02'
group by id
)B
ON A.id=B.id
When I join these two tables, I'm getting NULL values for the unmatched records.
I need to replace those NULL records to some hardcoded value say 'XYZ'.
Any guidance on how to achieve this please?
So the top level select needs to name which ID it is using (other DB's don't require this snowflake does), given you are selecting from A and b.id might be missing, it should be a.id
count_of_orders is not used, so currently the LEFT JOIN to B is pointless, given your question is about LEFT JOIN this must be the column you a referring to??
The replace NULL values can be done via COALESCE or NVL or ZEROIFNULL, given the only null thing is a count, zeroifnull seems to make sense here.
which all make me think your SQL needs to look like:
SELECT
a.id,
a.login_id,
a.count,
case
WHEN a.count = 0 then 'Cat_A'
WHEN a.count between 1 and 10 then 'Cat_B'
WHEN a.count > 10 then 'Cat_C'
WHEN a.count IS NULL THEN 'Cat D'
END as Category,
ZEROIFNULL(b.count_of_orders) as count_of_orders
FROM (
SELECT
id,
login_id,
min(ord_count) AS count
FROM table_1 AS X
JOIN table_2 AS Y
ON X.id_col = Y.id_col
WHERE date = '2022-02-02'
AND login_id = 'True'
group by id,login_id
) as A
LEFT JOIN (
SELECT
x.id,
COUNT(X.ord_no) AS count_of_orders
FROM table_1 as X
WHERE X.date = '2022-02-02'
group by x.id
)as B
ON A.id=B.id
The A sub-select really should use the aliases you named X, Y so we know which tables id, login_id, ord_count, & date all come from.
I am trying to write a query where I want to sum a price column based on the condition which is a subquery.
my query :
select
fund.FundName,
SUM(Case when (
Select Top 1 bitValue
from table 1
where table1.id = Company.id and table1.field = 25
) = 1 then price else 0 end) as 'TotalPrice'
from
Fund left outer join Company on Company.fundId=fund.id
group by
fund.fundName
It throws me error : Cannot perform an aggregate function on an expression containing an aggregate or a subquery.
What is the best alternative way to achieve this.
Hope this Works for your Case:
SELECT
FUND.FUNDNAME,
S.TotalPrice
FROM FUND
LEFT OUTER JOIN COMPANY ON COMPANY.FUNDID=FUND.ID
LEFT JOIN (SELECT CASE WHEN BITVALUE=1 THEN SUM(PRICE) ELSE 0 END as 'TotalPrice',table1.ID
from table 1
where table1.id = Company.id and table1.field = 25 GROUP BY table1.ID
) S ON S.ID=Company.id
GROUP BY
FUND.FUNDNAME
untested obviously with no sample data provided.
select fund.FundName
,SUM(Case when table1.id is not null then price else 0 end) as 'TotalPrice'
from Fund
left outer join Company on Company.fundId = fund.id
left outer join (
select distinct id
from table1
where field = 25
and bitvalue = 1
) table1 on table1.id = Company.id
group by fund.fundName
I'm trying to create a script that synchronizes Sales and Inventory tables. For that I wrote an UPDATE on the Inventory table (which has 1 record per item of inventory present) like this:
UPDATE TOP (q.QuantitySold) i
SET i.Converted = 1,
i.CartID = q.CartID,
i.ReservedDate = GETDATE()
FROM Inventory i
INNER JOIN
(
SELECT product.ProductID, sales.CartID, COUNT(sales.ID) AS QuantitySold
FROM Products product
INNER JOIN Sales sales ON sales.ProductID = product.ProductID
WHERE <conditions>
GROUP BY product.ProductID, sales.CartID
) q ON q.ProductID = i.ProductID
WHERE i.Converted = 0 AND i.CartID IS NULL
But it's not working, error says q.QuantitySold couldn't be bound.
Is there a way to update N records of inventory (equal to the quantity sold) without using a cursor? I refuse to give up like that.
Note: this is a simplified version of the actual query.
You could use ROW_NUMBER to enumerate the inventory items that you need to update.
WITH cteProducts AS(
SELECT product.ProductID, sales.CartID, COUNT(sales.ID) AS QuantitySold
FROM Products product
INNER JOIN Sales sales ON sales.ProductID = product.ProductID
WHERE <conditions>
GROUP BY product.ProductID, sales.CartID
),
cteInventory AS(
SELECT *,
ROW_NUMBER() OVER( PARTITION BY ProductID ORDER BY (SELECT NULL)) AS rn /*Change the ORDER BY for an actual column if needed, probably for FIFO*/
FROM Inventory
WHERE i.Converted = 0
AND i.CartID IS NULL
)
UPDATE i
SET i.Converted = 1,
i.CartID = q.CartID,
i.ReservedDate = GETDATE()
FROM cteInventory i
INNER JOIN cteProducts q ON q.ProductID = i.ProductID
WHERE i.rn <= q.QuantitySold;
This query return number of rows where Sum of Product's Quantity is equal to 0 and Product Name is 'XYZ'. But I want same result for each products. For example if I remove product name from where clause so it will bring SUM of every product where quantity is 0. I want it to return separately for each products. Products may increase in future. I have to first check how many distinct products are there in CustomerProduct table and then need to query same things for each product. How can I do that. Title might not is perfect, Please suggest/correct if it required to.
select Count(*) From
(select distinct VI.Name, Cp.ProductName
FROM VendorInfo VI inner join VendorTrading VT on VI.Id = VT.VendorId inner join CustomerProducts CP on VT.Id = CP.VendorTradingId
Where VT.Tradedate = '2015-12-25' and CP.ProductName = 'XYZ'
GROUP BY VI.Name, Cp.ProductName, CP.ProductQuantity
HAVING SUM( CP.ProductQuantity ) = 0) as x
Affan, can you add tsql script to create the tables with some data, so it is easier for us to assist. However if you simplify the query then you can get each product and vendor with zero ProductQuantity
select VI.Name, Cp.ProductName, SUM( CP.ProductQuantity )
FROM VendorInfo VI
inner join VendorTrading VT on VI.Id = VT.VendorId
inner join CustomerProducts CP on VT.Id = CP.VendorTradingId
Where VT.Tradedate = '2015-12-25'
GROUP BY VI.Name, Cp.ProductName
HAVING SUM( CP.ProductQuantity ) = 0
Tbl_cdr(ano,starttime)
Tbl_User(id,mobileno)
I want to count the rows from Tbl_cdr with condition omitting the rows (when ano = mobileno) and group by starttime.
any help ,Plz...
select c.starttime, count(*)
from Tbl_cdr c
where not exists (select 1 from Tbl_User u where u.mobileno = c.ano)
group by c.starttime
select count(*), c.StartTime
from Tbl_cdr c
left join Tbl_User u on c.ano = u.mobileno
where u.id is null
group by c.StartTime