【问题标题】:Query for Customers, total value of purchases, and total discounts given to Customers by Year按年份查询客户、采购总额、给予客户的总折扣
【发布时间】:2021-07-11 18:12:28
【问题描述】:

我使用的是罗斯文数据库。我想编写一个查询来显示客户、购买的总价值以及按年份给予客户的总折扣。我想显示 1996、1997、1998 年的所有客户。

下面是我正在使用的表格。

SELECT TOP (1000) [CustomerID]
      ,[CompanyName]
      ,[ContactName]
      ,[ContactTitle]
      ,[Address]
      ,[City]
      ,[Region]
      ,[PostalCode]
      ,[Country]
      ,[Phone]
      ,[Fax]
  FROM [Northwind].[dbo].[Customers]

SELECT TOP (1000) [OrderID]
      ,[CustomerID]
      ,[EmployeeID]
      ,[OrderDate]
      ,[RequiredDate]
      ,[ShippedDate]
      ,[ShipVia]
      ,[Freight]
      ,[ShipName]
      ,[ShipAddress]
      ,[ShipCity]
      ,[ShipRegion]
      ,[ShipPostalCode]
      ,[ShipCountry]
  FROM [Northwind].[dbo].[Orders]

SELECT TOP (1000) [OrderID]
      ,[ProductID]
      ,[UnitPrice]
      ,[Quantity]
      ,[Discount]
  FROM [Northwind].[dbo].[Order Details]

这是我写的查询:

SELECT  o.customerID, year(o.OrderDate) as Year,
        sum(od.UnitPrice * od.Quantity) as Total_value_of_purchase, 
        sum(od.UnitPrice * od.Quantity * od.Discount) as Total_discount_received,
        sum((od.UnitPrice * od.Quantity)-(od.UnitPrice * od.Quantity * od.Discount)) as Total_after_discount
FROM Customers as c
cross JOIN Orders as o

left outer join [Order Details] as od
on o.OrderID=od.OrderID

GROUP BY o.CustomerID, Year(o.OrderDate)
order by o.CustomerID, Year(o.OrderDate)

这是我得到的结果图片。

您会注意到,在某些情况下,客户可能不会每年都订购,所以我只得到了 234 个结果。有什么方法可以显示所有客户和所有 3 年?所以如果我有 91 个客户,结果将显示 91*3=273 结果。

您能否为我提供指导或帮助,以便我可以按照此解决此问题?

【问题讨论】:

    标签: sql-server tsql ssms


    【解决方案1】:

    我有一些更新。我尝试使用联合。

    SELECT c.CustomerID, y.YR,
            sum(od.UnitPrice * od.Quantity) as Total_value_of_purchase, 
            sum(od.UnitPrice * od.Quantity * od.Discount) as Total_discount_received,
            sum((od.UnitPrice * od.Quantity)-(od.UnitPrice * od.Quantity * od.Discount)) as Total_after_discount
    FROM (SELECT 1996 YR UNION ALL SELECT 1997 UNION ALL SELECT 1998) y(YR)
    CROSS JOIN Customers c
    LEFT OUTER JOIN Orders o ON c.CustomerID = o.CustomerID
    LEFT OUTER JOIN [Order Details] od ON o.OrderID = od.OrderID
    GROUP BY c.CustomerID, y.YR
    ORDER BY c.CustomerID, y.YR
    

    结果:https://ibb.co/N9T7pk2

    我确实得到了 273 个结果,但它没有给我每年的总数,而是给了我所有年份的总数。

    有什么建议吗?

    PS:我不是为了作业做这个。我真的很想找到解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-11
      • 1970-01-01
      • 1970-01-01
      • 2015-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多