Quantcast
Channel: SQLServerCentral » SQL Server 2014 » Development - SQL Server 2014 » Latest topics
Viewing all articles
Browse latest Browse all 3145

Why is this CTE so better solution then Cross Apply ?

$
0
0
Tables :CREATE TABLE [Production].[Products]( [productid] [int] IDENTITY(1,1) NOT NULL, [productname] [nvarchar](40) NOT NULL, [supplierid] [int] NOT NULL, [categoryid] [int] NOT NULL, [unitprice] [money] NOT NULL, [discontinued] [bit] NOT NULL, CONSTRAINT [PK_Products] PRIMARY KEY CLUSTERED ( [productid] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]GOCREATE TABLE [Production].[Categories]( [categoryid] [int] IDENTITY(1,1) NOT NULL, [categoryname] [nvarchar](15) NOT NULL, [description] [nvarchar](200) NOT NULL, CONSTRAINT [PK_Categories] PRIMARY KEY CLUSTERED ( [categoryid] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]GOI wrote this code using cross apply :select c.categoryid,a.productid,a.productname, a.unitpricefrom Production.Categories as ccross apply ( select productid, productname, unitprice from Production.Products as p where c.categoryid=p.categoryid order by categoryid, unitprice offset 0 rows fetch first 1 rows only) as aorder by categoryidgo My book suggested CTE like this :with CTE_min as ( select categoryid, min(unitprice) as mn from Production.Products group by categoryid)select p.categoryid, p.productid, p.productname, p.unitpricefrom Production.Products as pJOIN CTE_min as m on p.categoryid=m.categoryidand p.unitprice=m.mn ;This database is TSQL2012, I am learning for SQL Server MCSA. Exercise was to write a solution that uses a CTE to return the products with the lowest unit price per category. I done it but later I write this cross apply solution as well, i run Actual Execution plan and it was 88% for cross join and only 12% for CTE. My question is why is CTE so much better?English isn't my native, thanks in advance.

Viewing all articles
Browse latest Browse all 3145

Latest Images

Trending Articles



Latest Images