简体   繁体   中英

SQL SELECT with a Yes/No column to state whether Customer has associated Orders

I want to create a SQL statement that returns a list of Customers, such as:

SELECT Id, FirstName, LastName FROM Customer

That part is easy, obviously.

Now I want to create a variable column, such as HasOrders. I want this to be a dynamically generated bool column based on whether the Customer has one or more orders in an Order table. For the purpose of this question assume it's irrelevant whether an order is open or not, just whether any orders exist for that customer id.

I want the SELECT statement to return all Customers, not just Customers with Orders. I need to do further logic dependent on whether a Customer has orders or not.

I'm not sure whether this can be achieved with IF..ELSE, CASE, or a nested SELECT?

SELECT  a.ID, a.FirstName, a.Lastname,
        CASE WHEN COUNT(b.CustID) > 0 THEN 'YES' ELSE 'NO' END AS HasOrders
FROM    Customer a
        LEFT JOIN Orders b
            ON a.ID = b.CustID        -- <<== the linking column on both tables
GROUP   BY a.ID, a.FirstName, a.Lastname

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