Adding column contents in a SQL UNION query - sql

So far I have this query
SELECT
COUNT(f.code_id) as item_count,
f.code_desc
FROM
foo f
INNER JOIN foohistory fh ON f.history_id = fh.history_id
WHERE
MONTH(fh.create_dt) = 6
AND YEAR(fh.create_dr) = 2010
GROUP BY
f.code_desc
UNION ALL
SELECT
COUNT(b.code_id) as item_count,
b.code_desc
FROM
bar b
INNER JOIN barhistory bh ON b.history_id = bh.history_id
WHERE
MONTH(bh.create_dt) = 6
AND YEAR(bh.create_dr) = 2010
GROUP BY
b.code_desc
My goal is to UNION these two queries add SUM the 'item_count' columns foreach code_desc. Is this possible?

Without more information about the codes, like if it's possible that codes are mutually exclusive between the two tables, use:
SELECT x.code_desc,
SUM(x.item_count)
FROM (SELECT f.code_desc,
COUNT(f.code_id) as item_count
FROM foo f
JOIN foohistory fh ON f.history_id = fh.history_id
WHERE MONTH(fh.create_dt) = 6
AND YEAR(fh.create_dr) = 2010
GROUP BY f.code_desc
UNION ALL
SELECT b.code_desc,
COUNT(b.code_id) as item_count
FROM bar b
JOIN barhistory bh ON b.history_id = bh.history_id
WHERE MONTH(bh.create_dt) = 6
AND YEAR(bh.create_dr) = 2010
GROUP BY b.code_desc) x
GROUP BY x.code_desc

Yeah, doing something like this
SELECT Sum(unionedTable.item_count)
FROM
(
//your query
) as unionedTable

Related

Get the sum of a count column in SQL

I have the following query
SELECT
dtc.coupon_type_company_name,
COUNT(*) * dtc.coupon_type_company_coupon_amount AS 'Total_Coupon_To_Be_Used',
dtc.coupon_type_company_coupon_months_combinable
FROM
[dbo].[coupon_type_Company_User] dtcu
JOIN
coupon_type_Company dtc ON dtcu.coupon_type_Company_ID = dtc.id
JOIN
person p ON dtcu.userID = p.userID
WHERE
coupon_type_company_coupon_is_combinable = 1
OR coupon_type_company_has_coupon = 1
AND dtc.companyID = 1081
AND p.is_active = 1
GROUP BY
dtc.coupon_type_company_name,dtc.coupon_type_company_coupon_amount,
dtc.coupon_type_company_coupon_months_combinable
This returns the following:
What I want to have however is just one column and one row that should take the SUM of my middle column (count(*)*dtc.coupon_type_company_coupon_amount).
How could I achieve this and prevent doing this in my code backend (C#)
You can wrap your query like this:
SELECT SUM(Total_Coupon_To_Be_Used) AS the_sum
FROM (
your query
) s
Use a "Table Expression", as in:
select sum(Total_Coupon_To_Be_Used) from (
SELECT dtc.coupon_type_company_name,
count(*) * dtc.coupon_type_company_coupon_amount as 'Total_Coupon_To_Be_Used',
dtc.coupon_type_company_coupon_months_combinable
FROM [dbo].[coupon_type_Company_User] dtcu
JOIN coupon_type_Company dtc ON dtcu.coupon_type_Company_ID = dtc.id
JOIN person p ON dtcu.userID = p.userID
WHERE coupon_type_company_coupon_is_combinable = 1
or coupon_type_company_has_coupon = 1
and dtc.companyID = 1081
AND p.is_active = 1
GROUP BY
dtc.coupon_type_company_name,dtc.coupon_type_company_coupon_amount,
dtc.coupon_type_company_coupon_months_combinable
) x

How to use alias of a subquery to get the running total?

I have a UNION of 3 tables for calculating some balance and I need to get the running SUM of that balance but I can't use PARTITION OVER, because I must do it with a sql query that can work in Access.
My problem is that I cannot use JOIN on an alias subquery, it won't work.
How can I use alias in a JOIN to get the running total?
Or any other way to get the SUM that is not with PARTITION OVER, because it does not exist in Access.
This is my code so far:
SELECT korisnik_id, imePrezime, datum, Dug, Pot, (Dug - Pot) AS Balance
FROM (
SELECT korisnik_id, k.imePrezime, r.datum, SUM(IIF(u.jedinstven = 1, r.cena, k.kvadratura * r.cena)) AS Dug, '0' AS Pot
FROM Racun r
INNER JOIN Usluge u ON r.usluga_id = u.ID
INNER JOIN Korisnik k ON r.korisnik_id = k.ID
WHERE korisnik_id = 1
AND r.zgrada_id = 1
AND r.mesec = 1
AND r.godina = 2017
GROUP BY korisnik_id, k.imePrezime, r.datum
UNION ALL
SELECT korisnik_id, k.imePrezime, rp.datum, SUM(IIF(u.jedinstven = 1, rp.cena, k.kvadratura * rp.cena)) AS Dug, '0' AS Pot
FROM RacunP rp
INNER JOIN Usluge u ON rp.usluga_id = u.ID
INNER JOIN Korisnik k ON rp.korisnik_id = k.ID
WHERE korisnik_id = 1
AND rp.zgrada_id = 1
AND rp.mesec = 1
AND rp.godina = 2017
GROUP BY korisnik_id, k.imePrezime, rp.datum
UNION ALL
SELECT uu.korisnik_id, k.imePrezime, uu.datum, '0' AS Dug, SUM(uu.iznos) AS Pot
FROM UnosUplata uu
INNER JOIN Korisnik k ON uu.korisnik_id = k.ID
WHERE korisnik_id = 1
GROUP BY uu.korisnik_id, k.imePrezime, uu.datum
) AS a
ORDER BY korisnik_id
You can save a query (let's name it Query1) for the UNION of the 3 tables and then create another query that returns each row in the first query and calculates the sum of the rows that are before it (optionally checking that they are in the same group).
It should be something like this:
SELECT *, (
SELECT SUM(Value) FROM Query1 AS b
WHERE b.GroupNumber=a.GroupNumber
AND b.Position<=a.Position
) AS RunningSum
FROM Query1 AS a
However, it's more efficient to do that in the report.

How to Join two select statements

I have four tables. I wrote 2 queries independently and those are working. But what I want to do is join those two queries and generate one result.
Here is my code
Query #1
SELECT
pm.DATE
,pm.customer
,pm.gp_no AS Gatepass_Num
,pf.style
,pf.color
,pf.batch_no
,COUNT(pf.roll_no) AS Roll_QTY
,SUM(pf.meter) AS QTY
FROM
(packinglists_fabrics_items pf
,packinglists_main pm
WHERE
pf.p_id = pm.id
[AND pm.date between {DateR,RANGE1} and {DateR,RANGE2}]
[AND pm.customer_id = "{factory,false}"]
GROUP BY
pm.DATE, pm.gp_no, pf.style, pf.color, pf.batch_no)
Query #2:
SELECT
lo.DATE
,lo.customer_name
,flo.style
,flo.color
,flo.batch_no
,COUNT(flo.rowno) AS Roll_QTY
,SUM(flo.meter) AS QTY_Meter
FROM
loadinglists_fabrics_items flo, loadinglists lo
WHERE
flo.p_id = lo.id
[AND lo.date between {DateR,RANGE1} and {DateR,RANGE2}]
[AND lo.customer_id = "{factory,false}"]
GROUP BY
lo.DATE, flo.style, flo.color, flo.batch_no
batch_no is unique for loadinglists_fabrics_items table and packinglists_fabrics_items table
Result of query 1
Result of query 2
Expected output
Try like this, I assume that you are using SQL Server
SELECT A.*
,B.*
FROM (
SELECT pm.DATE
,pm.customer
,pm.gp_no AS Gatepass_Num
,pf.style
,pf.color
,pf.batch_no
,COUNT(pf.roll_no) AS Roll_QTY
,SUM(pf.meter) AS QTY
FROM packinglists_fabrics_items pf
,packinglists_main pm
WHERE pf.p_id = pm.id
AND pm.DATE BETWEEN {DateR
,RANGE1}
AND {DateR
,RANGE2}
AND pm.customer_id = "{factory,false}"
GROUP BY pm.DATE
,pm.gp_no
,pf.style
,pf.color
,pf.batch_no
) A
INNER JOIN (
SELECT lo.DATE
,lo.customer_name
,flo.style
,flo.color
,flo.batch_no
,COUNT(flo.rowno) AS Roll_QTY
,SUM(flo.meter) AS QTY_Meter
FROM loadinglists_fabrics_items flo
,loadinglists lo
WHERE flo.p_id = lo.id
AND lo.DATE BETWEEN {DateR
,RANGE1}
AND {DateR
,RANGE2}
AND lo.customer_id = "{factory,false}"
GROUP BY lo.DATE
,flo.style
,flo.color
,flo.batch_no
) B ON A.batch_no = B.batch_no

SQL Union Query

SELECT pv.PropertyID, COUNT(pv.VisitID) AS InitialVisit
FROM tblPAppointments pa INNER JOIN tblPropertyVisit pv ON pv.AppID = pa.AppID
WHERE pv.Status = 0
GROUP BY pv.PropertyID
UNION ALL
SELECT jv.PropertyID, COUNT(jv.JobVistID) AS JobVisit
FROM tblPAppointments pa INNER JOIN tblJobVisits jv ON jv.AppID = pa.AppID
WHERE jv.VisitStatus = 1
GROUP BY jv.PropertyID
I need to get InitialVisit count and JobVisit count in two separate columns.above query returns just two columns (PropertyID,InitialVisit).
Use a NULL as a placeholder for the column that there won't be any output for:
SELECT pv.PropertyID,
COUNT(pv.VisitID) AS InitialVisit,
NULL AS jobvisit
FROM tblPAppointments pa
JOIN tblPropertyVisit pv ON pv.AppID = pa.AppID
WHERE pv.Status = 0
GROUP BY pv.PropertyID
UNION ALL
SELECT jv.PropertyID,
NULL AS initialvisit,
COUNT(jv.JobVistID) AS JobVisit
FROM tblPAppointments pa
JOIN tblJobVisits jv ON jv.AppID = pa.AppID
WHERE jv.VisitStatus = 1
GROUP BY jv.PropertyID
This will return three columns. The column alias is necessary in the first query, but not in the second -- I aliased both to make it clear what is happening.
Be aware that using NULL like this in SQL Server will require you to use CAST/CONVERT on the NULL for data types other than INT because SQL Server defaults the NULL to an INT data type (as odd as that is).
An alternate query that doesn't use UNION:
SELECT x.propertyid,
COUNT(y.visitid) AS initialvisit,
COUNT(z.jobvisitid) AS jobvisit
FROM (SELECT pv.propertyid
FROM TBLPROPERTYVISIT pv
WHERE EXISTS (SELECT NULL
FROM TBLAPPOINTMENTS a
WHERE a.appid = pv.appid)
UNION
SELECT jv.propertyid
FROM TBLJOBVISIT jv
WHERE EXISTS (SELECT NULL
FROM TBLAPPOINTMENTS a
WHERE a.appid = jv.appid)) x
LEFT JOIN TBLPROPERTYVISIT y ON y.propertyid = x.propertyid
LEFT JOIN TBLJOBVISIT z ON z.propertyid = x.propertyid
GROUP BY x.propertyid
No need for a UNION at all. And you don't use tblPAppointments either
Edited to allow for no rows in one of the tables. Still one row output though
SELECT
ISNULL(pv2.PropertyID, jv2.PropertyID),
ISNULL(pv2.InitialVisit, 0),
ISNULL(jv2.JobVisit, 0)
FROM
(
SELECT pv.PropertyID, COUNT(pv.VisitID) AS InitialVisit
FROM tblPropertyVisit pv
WHERE pv.Status = 0
GROUP BY pv.PropertyID
) pv2
FULL OUTER JOIN
(
SELECT jv.PropertyID, COUNT(jv.JobVistID) AS JobVisit
FROM tblJobVisits jv
WHERE jv.VisitStatus = 1
GROUP BY jv.PropertyID
) jv2 ON pv2.PropertyID = jv2.PropertyID

Join SQL Query Problem?

First Select Statement:
SELECT
dbo.FG_FILLIN.PartNumber,
dbo.DropshipPackinglist.Shiplist_Qty,
dbo.DropshipPackinglist.Quantity
FROM dbo.FG_FILLIN INNER JOIN
dbo.DropshipPackinglist ON
dbo.FG_FILLIN.PartNumber = dbo.DropshipPackinglist.PartNumber
WHERE (dbo.FG_FILLIN.Batch = 'CIP_HK_6')
GROUP BY
dbo.FG_FILLIN.Batch,
dbo.FG_FILLIN.PartNumber,
dbo.FG_FILLIN.ItemNumber,
dbo.DropshipPackinglist.Shiplist_Qty,
dbo.DropshipPackinglist.Quantity
Result :
PartNumber Shiplist_Qty Quantity
P02-070161-00111-C100 6 3
P02-070161-10111-C100 6 3
2nd :
SELECT PartNumber,COUNT(Batch) AS Created
FROM dbo.FG_FILLIN
WHERE Batch='CIP_HK_6'
GROUP BY Batch,PartNumber
Result :
PartNumber Created
P02-070161-00111-C100 3
P02-070161-10111-C100 1
Joining this two Query I cant show this one: RESULT NEEDED
PartNumber Shiplist_Qty Quantity Created
P02-070161-00111-C100 6 3 3
P02-070161-10111-C100 6 3 1
It always show : when i Add Count(dbo.FG_FILLIN.Batch) as Created
PartNumber Shiplist_Qty Quantity Created
P02-070161-00111-C100 6 3 6
P02-070161-10111-C100 6 3 2
Any Advice.? Thanks In Regards!
Using a subselect:
SELECT f.PartNumber,
dpl.Shiplist_Qty,
dpl.Quantity,
(SELECT COUNT(Batch) AS Created
FROM dbo.FG_FILLIN x
WHERE x.batch = f.batch
AND x.partnumber = f.partnumber
GROUP BY Batch, PartNumber) AS created
FROM dbo.FG_FILLIN f
JOIN dbo.DropshipPackinglist dpl ON dpl.partnumber = f.partnumber
WHERE f.Batch = 'CIP_HK_6'
GROUP BY f.Batch, f.PartNumber, f.ItemNumber, dpl.Shiplist_Qty, dpl.Quantity
Using a JOIN to a derived table/inline view
SELECT f.PartNumber,
dpl.Shiplist_Qty,
dpl.Quantity,
x.created
FROM dbo.FG_FILLIN f
JOIN dbo.DropshipPackinglist dpl ON dpl.partnumber = f.partnumber
LEFT JOIN (SELECT t.partnumber,
t.batch,
COUNT(Batch) AS Created
FROM dbo.FG_FILLIN t
GROUP BY Batch, PartNumber) x ON x.partnumber = f.partnumber
AND x.batch = f.batch
WHERE f.Batch = 'CIP_HK_6'
GROUP BY f.Batch, f.PartNumber, f.ItemNumber, dpl.Shiplist_Qty, dpl.Quantity
Change "LEFT JOIN" to "JOIN" if you only want to see parts that have created values.