My table contains few rows, which has to be aggregated.
eg: Columns are sites, fuel, sales, date
when date ,sites and fuel is same I need to aggregate the sales column for those rows and have one row.( delete other rows or not to select those rows, since values are aggregated)
How can I do that simply in select query in sql?
eg
site, fuel, sale,date siteA, Diesel, 100, 2019-01-01 SiteA, Diesel, 300, 2019-01-01 siteB ,Ulp, 200, 2019-01-01 siteC,E10, 500, 2019-01-01
Output has to be;
site, fuel, sale,date siteA, Diesel, 400, 2019-01-01 siteB ,Ulp, 200, 2019-01-01 siteC,E10, 500, 2019-01-01
My sql is like;
select [CompanyCode] as 'Company Code', [Sitecode] as 'Site Code', [ProductCode] as 'Product Name', CONVERT(date, [InvDay]) as Date, SUM (CASE WHEN [Sales] ='NULL' THEN 0 WHEN [Sales] = '' then 0 ELSE CONVERT(decimal(10,4) ,[Sales] ) END) as 'Sale Volume' FROM [dbo].[2018-01] group by Companycode,Sitecode,ProductCode,date,Sales
Advertisement
Answer
Use group by
and sum()
aggregation
select site, fuel, date, sum(case when sales is null or sales='' then 0 else cast(sales as decimal(10,4)) end) as sale from tablename group by site, fuel, date
As per your answer – you’ve to remove sales column from group by
select [CompanyCode] as 'Company Code', [Sitecode] as 'Site Code', [ProductCode] as 'Product Name', CONVERT(date, [InvDay]) as Date, SUM (CASE WHEN [Sales] is null or [Sales] = '' then 0 ELSE CONVERT(decimal(10,4) ,[Sales] ) END) as 'Sale Volume' FROM [NEO_DB].[dbo].[Caltex-migration-2018-01] group by Companycode,Sitecode,ProductCode,CONVERT(date, [InvDay])