SQL 查看 - 获取单价、默认价格和客户价格

SQL View - Fetching Unit Price, Default Price & Customer Price

我希望有人能帮助我解决这个 SQL 问题。

我有一个屏幕,您可以在其中向订单添加产品。此订单是为可能有也可能没有商品特价的客户准备的。

基本上,我追求的是 3 个数字:

为了简单起见,我有下表

订单行

价目表

RatecardClient(默认主费率卡为 ID 1)

价目表产品

产品有一个 ID,但也可以有一个产品变体 ID

我想为 OrderLine 创建一个视图,其中包含该产品的输入价格、默认价目表价格和特价。

我想要一个视图给我:

产品编号 单价从 "OrderLine" RatecardPrice 来自 "RatecardProduct" 与 "Ratecard" 相关且 RatecardId = 1(将始终存在)

ClientRatecardPrice(取决于此价目表中是否存在客户/产品/变体的现有价目表和条目)

我真的很希望有人能让我从这里开始,因为我真的很挣扎!

提前致谢!

我对价格列的位置以及 RateCardProduct 如何连接到 RateCard 做了一些假设。如果您包含删除额外列的实际 table 定义会更好。但是根据您可以在我的 table defs 中看到的假设,此查询应该可以满足您的需求。

create table ClientOrder(OrderID int, ClientID int)
create table OrderLine(OrderId int,ProductId int,ProductVariationId int, UnitPrice decimal(10,2))
create table Ratecard(RateCardId int,RatecardName varchar(50)) -- has default 1
create table RateCardClient(RatecardClientId int,RatecardId int,ClientId int) 
create table RateCardProduct(RatecardProductId int, RateCardId int, ProductId int, ProductVariationId int, Price decimal(10,2))

select Clientorder.ClientID, ClientOrder.OrderID, OrderLine.ProductID, OrderLine.ProductVariationId,
    OrderLine.UnitPrice as UnitPrice,
    P1.Price as RateCardPrice,
    P2.Price as ClientRateCardPrice
from ClientOrder
Join OrderLine on OrderLine.OrderID=ClientOrder.OrderID
-- Get the default price
join RateCardProduct P1 on P1.RateCardID=1 
    and P1.ProductId=OrderLine.ProductId
    and isnull(P1.ProductVariationID,0)=isnull(OrderLine.ProductVariationID,0)
-- Get the customer specific price
left join RateCardClient on RateCardClient.ClientID=ClientOrder.ClientID
left join RateCardProduct P2 on P2.RateCardID=RateCardClient.RateCardID 
    and P2.ProductId=OrderLine.ProductId
    and isnull(P2.ProductVariationID,0)=isnull(OrderLine.ProductVariationID,0)