You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

创建视图时在子查询中使用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 COALESCE prevents the average from returning NULL (for example, if a state has no cars in inventory). You can swap the 0 fallback with another value like NULL or a default average if that makes more sense for your use case.
  • Purchased Cars Filter: The INNER JOIN to CustomerPurchase (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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:50:21