I need help rewriting the following query as I need to group by the aliases and derived tables appear to be the only path open to me. I cannot group by Type and SalesDatabase as I get an invalid column error.
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
Any help appreciated.
The query as you have written is correct, if you intend to produce one row PER SB.NAME. It means that you could have
However, if you want to group by SalesType, then use this GROUP BY