1

我需要帮助重写以下查询,因为我需要按别名分组,派生表似乎是对我开放的唯一路径。由于出现无效列错误,我无法按类型和 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    

任何帮助表示赞赏。

4

2 回答 2

1

如果您打算为每个 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
于 2012-11-13T23:09:50.377 回答
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  
于 2012-11-13T23:03:54.010 回答