﻿/****** Object:  View [dbo].[v_OrderStatus]    Script Date: 17/03/2023 08:48:45 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO



CREATE VIEW [dbo].[v_OrderStatus]
AS

WITH cteDoorGroup AS
(
	SELECT	 OrderId
			,COUNT(DISTINCT TypeId) AS NumType
			,SUM(Quantity) AS NumDoors
			,SUM(Quantity*UnitCost) AS TotCost
	FROM	Door
	GROUP BY OrderId
)

SELECT
	 ord.OrderId
	,ord.CompanyId
	,ord.OrderExtCode
	,ord.DateIns
	,ord.UserIdIns
	,ord.DateMod
	,ord.UserIdMod
	,ord.STATUS as OrderStatus
	,ord.OrderDescript
	,ISNULL(cte.NumType, 0) AS NumType
	,ISNULL(cte.NumDoors, 0) AS NumDoors
	,ISNULL(cte.TotCost, 0) AS TotCost
	--,dbo.Door.DoorId
	--,dbo.Door.OrderId
	--,dbo.Door.TypeId
	--,dbo.Door.DoorExtCode
	--,dbo.Door.DateIns
	--,dbo.Door.UserIdIns
	--,dbo.Door.DateMod
	--,dbo.Door.UserIdMod
	--,dbo.Door.DoorDescript
	--,dbo.Door.Quantity
	--,dbo.Door.UnitCost
	
FROM dbo.[Order] as ord
LEFT OUTER JOIN cteDoorGroup cte ON ord.OrderId = cte.OrderId
GO