创建视图时在子查询中使用COALESCE,处理客户名称空值为NA
Solution: Create View with COALESCE for Customer Names and Subquery Average
Got it, let's fix and complete your view code to meet all your requirements:
IF OBJECT_ID ('V_PrixSuperieurMoyenne','V') IS NOT NULL DROP VIEW V_PrixSuperieurMoyenne; GO CREATE VIEW V_PrixSuperieurMoyenne AS SELECT CS.[State], CI.ListPrice, CI.CarInventoryID, -- Replace NULL customer names with "NA" COALESCE(CONCAT(C.Name, ' ', C.FirstName), 'NA') AS 'Nom du Client', -- Use COALESCE in the subquery to handle NULL average values COALESCE( (SELECT AVG(CI_Sub.ListPrice) FROM CarInventory CI_Sub INNER JOIN CarState CS_Sub ON CS_Sub.CarInventoryID = CI_Sub.CarInventoryID -- Match the state to calculate average per state (adjust filter as needed) WHERE CS_Sub.[State] = CS.[State]), 0 -- Fallback value if no cars exist for the state (adjust to your preference) ) AS AverageListPricePerState FROM CarInventory CI INNER JOIN CarState CS ON CS.CarInventoryID = CI.CarInventoryID -- Join to purchase records to only include bought cars INNER JOIN CustomerPurchase CP ON CP.CarInventoryID = CI.CarInventoryID -- Left join to customers to handle cases where purchase has no linked customer LEFT JOIN Customer C ON CP.CustomerID = C.CustomerID; GO
Key Details to Note:
- NULL Customer Name Handling: The
COALESCE(CONCAT(C.Name, ' ', C.FirstName), 'NA')ensures if either the last name or first name is NULL (or both), we display "NA" instead of a partial name or NULL value. - COALESCE in Subquery: Wrapping the average calculation with
COALESCEprevents the average from returning NULL (for example, if a state has no cars in inventory). You can swap the0fallback with another value likeNULLor a default average if that makes more sense for your use case. - Purchased Cars Filter: The
INNER JOINtoCustomerPurchase(adjust the table name/columns to match your actual schema) ensures we only include cars that have been bought by customers, not just inventory. - Schema Adjustments: I assumed common foreign key relationships (like
CS.CarInventoryID = CI.CarInventoryID)—tweak these joins to match your database's actual table structure.
内容的提问来源于stack exchange,提问作者Emil Grozdanov
相关产品推荐
相关产品推荐

