如何消除答案中的重复值

时间:2018-04-09 21:14:50

标签: sql-server sum duplicates distinct

我使用Microsoft SQL Server中的AventureWorks2014数据库。我需要创建一个视图,显示CustomerID,全名和通过网络销售给客户的总金额。

我的问题是,我似乎无法获得与单个客户相对应的值,以便单个客户在我的结果中回答单行。这是我的代码,任何帮助将不胜感激。我基本上需要在网上显示销售给客户的总金额。

if object_id('vTotalWebSalesPerCustomer', 'v') is not null
    drop view vTotalWebSalesPerCustomer;
go

create view vTotalWebSalesPerCustomer
as
    select distinct 
        c.CustomerID,
        ltrim(rtrim(concat(concat(concat(concat(concat(concat(concat(p.Title, ' '), p.LastName), ', '), ' '), p.FirstName), ' '), p.Suffix))) as NomClient,
        soh.TotalDue
    from
        [Sales].[Customer] as c
    left join 
        [Person].[Person] as p on c.CustomerID = p.BusinessEntityID
    left join 
        [Sales].[SalesOrderHeader] as soh on soh.CustomerID = c.CustomerID
    where 
        year(soh.OrderDate) = 2014 
        and datepart(quarter, soh.OrderDate) = 1 
        and [OnlineOrderFlag] = 1
go

select * 
from vTotalWebSalesPerCustomer

由于

3 个答案:

答案 0 :(得分:0)

您可以使用deploymentResult上的VIEW使用以下GROUP BY

SELECT

注意:您只需要一个CONCAT函数来连接所有字符串值。

答案 1 :(得分:0)

DISTINCT过滤结果行以删除重复项。我认为你想要的是聚合行。也许这会做你想要的:

create view vTotalWebSalesPerCustomer as
    select      c.CustomerID,
                        ltrim(rtrim(concat(concat(concat(concat(concat(concat(concat(p.Title, ' '), p.LastName), ', '), ' '), p.FirstName), ' '), p.Suffix))) as NomClient,
                        sum(soh.TotalDue) as TotalDue
    from [Sales].[Customer] as c
    left join [Person].[Person] as p on c.CustomerID = p.BusinessEntityID
    left join [Sales].[SalesOrderHeader] as soh on soh.CustomerID = c.CustomerID
    where year(soh.OrderDate) = 2014 and datepart(quarter, soh.OrderDate)=1 and [OnlineOrderFlag] = 1
    group by c.CustomerID,NomClient

请注意,我删除了您想要合计金额的不同的sum运算符,并按客户ID和名称字段进行分组(SQL Server要求您在GROUP BY所有结果列中列出没有汇总的。)

答案 2 :(得分:0)

听起来你需要使用GROUP BY和SUM(),例如:

SELECT column-names
 FROM table-name
WHERE condition
GROUP BY column-names
ORDER BY column-names

如:

SELECT SUM(O.TotalPrice), C.FirstName, C.LastName
  FROM [Order] O JOIN Customer C 
    ON O.CustomerId = C.Id
 GROUP BY C.FirstName, C.LastName
 ORDER BY SUM(O.TotalPrice) DESC

会回来:

Sum         FirstName   LastName
117483.39   Horst       Kloss
115673.39   Jose        Pavarotti
113236.68   Roland      Mendel
57317.39    Patricia    McKenna
52245.90    Paula       Wilson
34101.15    Mario       Pontes
32555.55    Maria       Larsson