how to do avg() in from count()sql - tsql

I have this T-sql to get count for each sell rep to a customer during current month
I want to ask how can apply avg function to get avg visit for current month
SELECT COUNT(VisitTracking.customerID) AS #VISIT,
MAX(VisitTracking.visitID) AS VisitID,
Customers.title AS Title,
Customers.firstName AS [First Name],
Customers.LastName AS [Last Name],
Company.companyName AS [Company Name],
MAX(VisitTracking.DateVisited) AS [Date Visited],
CONVERT(DATE, MAX(VisitTracking.nextVisit)) AS [Next Visit],
Customers.customerID
FROM VisitTracking
INNER JOIN Customers ON VisitTracking.customerID = Customers.customerID
INNER JOIN Customer_Company ON Customers.customerID = Customer_Company.customerID
INNER JOIN Company ON Customer_Company.companyID = Company.companyID
WHERE VisitTracking.DateVisited BETWEEN '11/01/2012' AND '11/31/2012'
GROUP BY Customers.title, Customers.firstName, Customers.LastName, Company.companyName, Customers.customerID

Have you tried compute?
SELECT [sParID], count([sParID]) as '#sID'
FROM [docSVsys]
group by [sParID]
order by [sParID]
compute avg(count([sParID]))

Why not a sub select? Yeah, I know, sub select are NASTY, NOT NICE and don't perform as well. But they do get the job done when producing data for reports and analysis, so, maybe:
SELECT AVG(a.#VISIT) FROM (SELECT COUNT(VisitTracking.customerID) AS #VISIT,
MAX(VisitTracking.visitID) AS VisitID,
Customers.title AS Title,
Customers.firstName AS [First Name],
Customers.LastName AS [Last Name],
Company.companyName AS [Company Name],
MAX(VisitTracking.DateVisited) AS [Date Visited],
CONVERT(DATE, MAX(VisitTracking.nextVisit)) AS [Next Visit],
Customers.customerID
FROM VisitTracking
INNER JOIN Customers ON VisitTracking.customerID = Customers.customerID
INNER JOIN Customer_Company ON Customers.customerID = Customer_Company.customerID
INNER JOIN Company ON Customer_Company.companyID = Company.companyID
WHERE VisitTracking.DateVisited BETWEEN '11/01/2012' AND '11/31/2012'
GROUP BY Customers.title, Customers.firstName, Customers.LastName, Company.companyName, Customers.customerID) AS a

Related

Subqueries and Combining Queries together

I have a problem I've been working on. I've broken it down to a couple of steps below. I have trouble combining all the queries together to solve the following:
Find members who have spent over $1000 in departments that have
brought in more than $10000 total ordered by the members' id.
Schema:
departments(id, name)
products (id, name, price)
members(id, name, number, email, city, street_name, street_address)
sales(id, department_id, product_id, member_id, transaction_date
Step 1)
I found the departments that have brought in more than 10,000$
select s.department_id
from sales s join products p on
s.product_id = p.id
group by s.department_id
having sum(price) > '10000'
Step 2) I found the members and the departments that they shop in
select *
from members m
join sales s
on m.id = s.member_id
join departments d
on d.id = s.department_id
Step 3) I combined 1 and 2 to find members taht shop in departments that have brought in more than 10,000
select *
from members m
join sales s
on m.id = s.member_id
join departments d
on d.id = s.department_id
where s.department_id in
(select s.department_id
from sales s join products p on
s.product_id = p.id
group by s.department_id
having sum(price) > '10000')
Step 4) I found members and their id, email, total_spending > 1,000$
select m.id, m.name, m.email, sum(price) as total_spending
from members m join sales s on
m.id = s.member_id
join products p on
p.id = s.product_id
group by m.id
having sum(price) > '1000'
Step 5)
All of the steps work individually but when I put them together in my attempt:
select m.id, m.name, m.email, sum(price) as total_spending
from members m join sales s on
m.id = s.member_id
join products p on
p.id = s.product_id
where m.id in (select distinct m.id
from members m
join sales s
on m.id = s.member_id
join departments d
on d.id = s.department_id
where s.department_id in
(select s.department_id
from sales s join products p on
s.product_id = p.id
group by s.department_id
having sum(price) > '10000'))
group by m.id
having sum(price) > '1000'
The output is wrong. (This is on CodeWars) If someone could point me in the right direction that would be really great! Thank you.
Try to group by member_id and department_id:
select s.member_id,s.department_id,sum(p.price) as total_spending
from members m
join sales s on m.id = s.member_id
join products p on p.id = s.product_id
where s.department_id in (
select s.department_id
from sales s
join products p on s.product_id = p.id
group by s.department_id
having sum(p.price) > 10000 -- the departments which brought in more than $10000 total
)
group by s.member_id,s.department_id
having sum(p.price) > 1000 -- who have spent over $1000 in one department
And if you need you will able to calc how much spent each of members:
select member_id,sum(total_spending) total
from
(
-- the first query is here
) q
group by member_id

Problems with Postgresql ERROR: subquery uses ungrouped column "ev.title" from outer query

I have a query like this:
select c.id, c.name, c.website, c.longdescription, c.description, c.email,
(SELECT jsonb_agg(ev) FROM
(SELECT ev.title, ev.description, ev.longdescription,
(SELECT jsonb_agg(ed) FROM
(SELECT ed.startdate, ed.enddate, ed.id WHERE ed.id notnull)ed) as dates, ev.id WHERE ev.id notnull) ev) as events,
(SELECT jsonb_agg(ca) FROM (SELECT ct.zip, ca.id, ca.street1, ca.street2, ca.addresstype_id, ST_Y(ca.geopoint::geometry) as latitude, ST_X(ca.geopoint::geometry) as longitude
WHERE ca.id notnull)ca) as addresses
FROM companies c
LEFT JOIN events ev ON ev.company_id = c.id
LEFT JOIN companyaddresses ca ON ca.company_id = c.id
LEFT JOIN cities ct ON ct.id = ca.city_id
LEFT JOIN eventdates ed ON ed.event_id = ev.id
GROUP by c.id
I am getting the error "ERROR: subquery uses ungrouped column "ev.title" from
outer query Position: 125".
Can't figure out how to group it correctly for the subqueries. Any suggestions?
Give this a try:
SELECT c.id, c.name, c.website, c.longdescription, c.description, c.email,
    (SELECT jsonb_agg(ev) FROM
        (SELECT even.title, even.description, even.longdescription,
            (SELECT jsonb_agg(ed) FROM
                (SELECT eventdates.startdate, eventdates.enddate, eventdates.id FROM eventdates WHERE eventdates.event_id = even.id)ed) as dates,
        even.id FROM events even WHERE even.company_id = c.id) ev) as events,
jsonb_agg((SELECT ca FROM (SELECT ct.zip, ca.id, ca.street1, ca.street2, ca.addresstype_id, ST_Y(ca.geopoint::geometry) as latitude, ST_X(ca.geopoint::geometry) as longitude WHERE ca.id notnull)ca)) as addresses
FROM companies c
LEFT JOIN companyaddresses ca ON ca.company_id = c.id
LEFT JOIN cities ct ON ct.id = ca.city_id
Group by c.id

Join two queries become one subquery

I want to ask how to combine these two queries become one subquery?
select c.CustomerName, A.Qty
from Customer c join (select s.CustomerID, pd.Date, s.Qty
from Period pd join Sales s on pd.TimeID = s.TimeID) A on c.CustomerID = A.CustomerID
where #Date = A.Date
and
select sum(case when (pd.Date between '2010-03-15' and #Date) then s.Qty else 0 end) as TotalQty
from Period pd full join Sales s on pd.TimeID = s.TimeID full join Customer c on s.CustomerID = c.CustomerID
group by c.CustomerName, c.CustomerID
They should result one table contains these following columns: CustomerName, Qty, and TotalQty. I've tried many ways but they didn't work at all. Really hope your help, thanks.
Answering your question assuming you are looking at the result as one row and not "column" :
select c.CustomerName, A.Qty,(select sum(case when (pd.Date between '2010-03-15' and #Date) then s.Qty else 0 end)
from Period pd full join Sales s on pd.TimeID = s.TimeID full join Customer c on s.CustomerID = c.CustomerID
group by c.CustomerName, c.CustomerID
) as TotalQty
from Customer c join (select s.CustomerID, pd.Date, s.Qty
from Period pd join Sales s on pd.TimeID = s.TimeID) A on c.CustomerID = A.CustomerID
where #Date = A.Date
If you still want the result as a single column , google "row to column transpose"

How to modify this query to show the number of seats in each active event?

I have the following database design:
Users Table: NetworkID, Name, BadgeNo, DepartmentCode
Events Table: ID, Title, Description, Location, StartDateTime, EndDateTime, NumberOfSeats, IsActive
BookingDetails Table: BookingID, EventID, NetworkID
I need to come up with a query that shows the number of seats, number of bookings and number of remaining (or availble) seats in each event. I wrote a query that shows the number of seats and number of bookings. Now, I need to find the number of remaining (or available) seats which is equal to (number of seats - number of bookings). So could you please help me in modifying it to find this requirement?
My Query:
SELECT dbo.Events.Title, dbo.Events.Description, dbo.Events.Location, dbo.Events.NumberOfSeats, COUNT(DISTINCT dbo.BookingDetails.NetworkID)
AS [Number of Bookings]
FROM dbo.BookingDetails INNER JOIN
dbo.Users ON dbo.BookingDetails.NetworkID = dbo.Users.NetworkID RIGHT OUTER JOIN
dbo.Events ON dbo.BookingDetails.EventID = dbo.Events.ID
WHERE (dbo.Events.IsActive = 1)
GROUP BY dbo.Events.Title, dbo.Events.Description, dbo.Events.Location, dbo.Events.NumberOfSeats
SELECT dbo.Events.Title, dbo.Events.Description, dbo.Events.Location,
dbo.Events.NumberOfSeats, COUNT(DISTINCT dbo.BookingDetails.NetworkID) AS [Number of Bookings],
dbo.Events.NumberOfSeats - COUNT(DISTINCT dbo.BookingDetails.NetworkID) AS RemainingSeats
FROM dbo.BookingDetails INNER JOIN
dbo.Users ON dbo.BookingDetails.NetworkID = dbo.Users.NetworkID RIGHT OUTER JOIN
dbo.Events ON dbo.BookingDetails.EventID = dbo.Events.ID
WHERE (dbo.Events.IsActive = 1)
GROUP BY dbo.Events.Title, dbo.Events.Description, dbo.Events.Location, dbo.Events.NumberOfSeats
SELECT result.t, result.d, result.l, result.c, result.r, result.c-result.r
FROM (SELECT dbo.Events.Title t, dbo.Events.Description d, dbo.Events.Location l, dbo.Events.NumberOfSeats c, COUNT(DISTINCT dbo.BookingDetails.NetworkID) r AS [Number of Bookings] FROM dbo.BookingDetails INNER JOIN dbo.Users ON dbo.BookingDetails.NetworkID = dbo.Users.NetworkID RIGHT OUTER JOIN dbo.Events ON dbo.BookingDetails.EventID = dbo.Events.ID WHERE (dbo.Events.IsActive = 1) GROUP BY dbo.Events.Title, dbo.Events.Description, dbo.Events.Location, dbo.Events.NumberOfSeats) result
Try this query.

SQL Join Statement Issue

I'm tring to grab all fields from the latest Cash record, and then all fields from the related TransactionInfo record. I can't quite get this to work yet:
select t.*, top 1 c.* from Cash c
inner join TransactionInfo t
on c.TransactionID = t.id
order by c.createdOn desc
select top 1 *
from Cash c
inner join TransactionInfo t on c.TransactionID = t.id
order by createdOn desc
What's that top 1 doing there? If you only want one row then the TOP(1) must come first:
SELECT TOP(1) t.*, c.*
FROM Cash c
INNER JOIN TransactionInfo t
ON c.TransactionID = t.id
ORDER BY c.createdOn DESC
select t.,c.
from (Select top 1 * from Cash order by createdOn desc
) c
inner join TransactionInfo t
on c.TransactionID = t.id
order by createdOn desc
DOn;t use select * especially with a join, it wastes server resources.
SELECT c.*, t.* FROM cash c, transactioninfo t
WHERE c.infoid = t.id AND c.createdOn = (SELECT max(createdOn) FROM cash WHERE infoId = t.id) ORDER BY transactiontabledate desc
You need to find the record with the latest date from the cash table for each transactionId and use that also to filter it out in your query.