简体   繁体   中英

SQL Join to count based on query results

I'm getting hung up trying to count records from one table based upon the results of a query. My table looks like this:

parent_id |  site_id  | description
-----------------------------------
A1           1          FL
A1           2          NJ
A1           A1         Company_A

First I created a query to give me the company name on the same row as the state (description). My initial query is:

SELECT master.description, sites.description, sites.site_id 
FROM sites sites
INNER JOIN sites master 
  ON sites.parent_id = master.site_id

Which results in:

Company_A     FL    1
Company_A     DE    2

So far so good. What I want to do, though, is count the number of orders from the table for each , even where the number of orders are 0. 表中每个的订单数量,即使订单数量为0。

I'm stumped on how to count from the table based on the results of my query? 表中进行计数? Any help on this join would be appreciated.

UPDATE: Almost there! Here's what is working:

SELECT master.description, sites.description, count(order_id) orderCount
FROM sites sites
INNER JOIN sites master
ON sites.parent_id = master.site_id
LEFT JOIN orders o
ON sites.site_id = o.site_id
WHERE sites.site_type = 3
GROUP BY master.description, sites.description, sites.site_id
ORDER BY master.description

The only issue I have left is if I add a date range I get the correct results, but any sites with ZERO orders for that period are not shown. So if I add:

WHERE sites.site_type = 3 AND o.order_date > '2015-10'

I get the correct result but only for sites with orders during that period. What am I missing?

This should meet your expectations:

SELECT master.description, sites.description, sites.site_id,
ISNULL((SELECT COUNT(*) FROM Orders o where master.siteId = o.siteId),0) as ordersCount
FROM sites sites
INNER JOIN sites master 
  ON sites.parent_id = master.site_id

You can solve this pretty easily with a LEFT Join and then a count on order id. It's important to not count the row count(*) because that would return a value of 1 even when there's no orders

Additionally any filtering on the orders table needs to be done inside the JOIN.

SELECT master.description, sites.description, sites.site_id 
       ,count(order_id) order_count 
FROM sites sites
INNER JOIN sites master 
  ON sites.parent_id = master.site_id
LEFT JOIN orders o
ON master.site_id = o.Site_id
   and   o.order_date > '2015-10'
WHERE
       sites.site_type = 3 
GROUP by
 master.description, sites.description, sites.site_id 

You didn't describe your Order table so I'm guessing at the join criteria

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM