使用派生表按ALIAS分组

时间:2012-11-13 22:54:09

标签: sql sql-server sql-server-2008

我需要帮助重写以下查询,因为我需要按别名分组,派生表似乎是唯一对我开放的路径。我无法按类型和SalesDatabase进行分组,因为我收到了无效的列错误。

SELECT    'Transactions'        AS Type,  
          'SalesDb'             AS SalesDatabase,  
          COUNT (B.Id)          AS Total,  
          CASE 
              WHEN SB.name LIKE '%Online%'      THEN 'Online'   
              WHEN SB.name LIKE '%RetailSale%'  THEN 'Retail'   
              ELSE 'Bricks'   
          END AS SalesType,    
          ISNULL( SUM( CASE WHEN datediff( d, b.Inserted, getDate() ) <  1 THEN 1 ELSE 0 END ), 0 ) AS SalesPeriod0,          
          ISNULL( SUM( CASE WHEN datediff( d, b.Inserted, getDate() ) >=  1 and datediff( d, b.Inserted, getDate() ) < 8 THEN 1 ELSE 0 END ), 0 ) AS SalesPeriod1to7 ,         
          ISNULL( SUM( CASE WHEN datediff( d, b.Inserted, getDate() ) >= 8 THEN 1 ELSE 0 END ), 0 ) AS SalesPeriod8p  
FROM SalesItem B WITH (NOLOCK)  
INNER JOIN SalesBatch SB WITH (NOLOCK) ON SB.Id  = B.BatchId    
GROUP BY SB.NAME    

任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:1)

如果您打算生成一行PER SB.NAME,那么您编写的查询是正确的。这意味着你可以拥有

SB.NAME    | SalesType   | ...
ABC        | Online      | ...
DEF        | Online      | ...
XYZ        | Retail      | ...
DEF1       | Retail      | ...

但是,如果要按SalesType进行分组,请使用此GROUP BY

GROUP BY CASE 
          WHEN SB.name LIKE '%Online%'      THEN 'Online'   
          WHEN SB.name LIKE '%RetailSale%'  THEN 'Retail'   
          ELSE 'Bricks'   
      END

答案 1 :(得分:0)

无需对常量Type和SalesDatabase进行分组。

GROUP BY SB.NAME,  
          CASE 
              WHEN SB.name LIKE '%Online%'      THEN 'Online'   
              WHEN SB.name LIKE '%RetailSale%'  THEN 'Retail'   
              ELSE 'Bricks'   
          END