SQL Server的derived table 临时表

例子1:

创建一个查询

SELECT ProductID, Name, ListPrice,    
    CASE WHEN ListPrice > 1000 THEN N'High' ELSE N'Normal' END AS PriceType
FROM SalesLT.Product

为了进一步查询,而又不增加它的复杂度。这时,可以创建一个derived table。

它基于上一次的查询新建的项。

SELECT DerivedTable.ProductID, DerivedTable.Name, DerivedTable.ListPrice
FROM    
    (        
        SELECT ProductID, Name, ListPrice,        
        CASE WHEN ListPrice > 1000 THEN N'High' ELSE N'Normal' END AS PriceType        
        FROM SalesLT.Product    
    ) AS DerivedTable
WHERE DerivedTable.PriceType = N'High';

例子2:

为了满足货物和重量要求。

SELECT ProductID, Name, Weight, ListPrice,       
    CASE WHEN Weight > 1000 THEN N'Heavy' ELSE N'Normal' END AS WeightType
FROM SalesLT.Product;

查询重货物,并且价格高于2000。

SELECT DerivedTable.ProductID, DerivedTable.Name, DerivedTable.Weight, DerivedTable.ListPrice
FROM    (        
    SELECT ProductID, Name, Weight, ListPrice,               
    CASE WHEN Weight > 1000. THEN N'Heavy' ELSE N'Normal' END AS WeightType        
    FROM SalesLT.Product    
    ) AS DerivedTable
WHERE DerivedTable.WeightType = N'Heavy' AND DerivedTable.ListPrice > 2000;

这就是derived table。

猜你喜欢

转载自blog.csdn.net/figosoar/article/details/131720458