我的表包含几行,这些行必须汇总。
例如:列为sites, fuel, sales, date
当日期,地点和燃料相同时,我需要汇总这些行的销售列并有一行。(删除其他行或不选择那些行,因为值是聚合的)
我该如何简单地在sql中选择查询呢?
例如
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
输出必须为;
site, fuel, sale,date
siteA, Diesel, 400, 2019-01-01
siteB ,Ulp, 200, 2019-01-01
siteC,E10, 500, 2019-01-01
我的sql就像;
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
答案 0 :(得分:2)
使用group by
和sum()
聚合
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
根据您的回答-您必须从“分组依据”中删除销售列
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])