【发布时间】:2022-11-17 00:51:46
【问题描述】:
我正在努力实现以下结果;
| Customer | Purchase Total ($) |
|---|---|
| Customer A | 1234.56 |
| Customer B | 5678.90 |
| Customer C | |
| Customer D | |
| Customer E | 91011.23 |
表结构如下;
| Table Name | Fields |
|---|---|
| Invoice | InvoiceId, InvoiceType, CustomerId, DateIssued |
| Invoice Lines | LineId, InvoiceId, ProductId, Date, Price, Quantity, LineTotal |
| Product | ProductId, Code, name |
| Customer | CustomerId, Status, Region, Code, Name |
我必须使用以下过滤器得出结果;
| Filter | Value |
|---|---|
| Product.Code | GTN |
| Invoice.InvoiceType | All invoices (Returns and Sales) are stored in the same table hence, in order to obtain correct result, I need to subtract returns from sales) Sales Invoice Type is 8 and Returns Invoice Type is 3 |
| Customer.Status | 0 |
| Customer.Region | London |
| Customer.Code | Starts with M |
| Invoice.Date | Year: 2022 Month: 10 |
我尝试了什么: 我尝试了很多其他的东西,下面是我最新的代码,但我得到了错误的结果。
SELECT C.Name,
(SELECT SUM(IL.LineTotal)
FROM Invoice I
INNER JOIN InvoiceLine IL ON I.InvoiceId= IL.InvoiceId
INNER JOIN Product P ON IL.ProductId = P.ProductId
WHERE IL.CustomerId = C.CustomerId AND P.CODE LIKE 'GTN.%' AND I.TRCODE = 8 AND YEAR(IL.Date) = 2022 AND MONTH(IL.Date) = 10 AND C.Code LIKE 'M.%' AND C.Region = 'London') -
(SELECT SUM(LI.LineTotal)
FROM Invoice I
INNER JOIN InvoiceLine IL ON I.InvoiceId= IL.InvoiceId
INNER JOIN Product P ON IL.ProductId = P.ProductId
WHERE IL.CustomerId = C.CustomerId AND P.CODE LIKE 'WLT.%' AND I.TRCODE = 3 AND YEAR(IL.Date) = 2022 AND MONTH(IL.Date) = 10 AND C.Code LIKE 'M.%' AND C.Region = 'London') AS TOTAL
FROM Invoice I
LEFT JOIN Customer C ON I.CustomerId = C.CustomerId
WHERE C.Code LIKE 'M.%'
GROUP BY C.CustomerId, C.Code, C.Name
ORDER BY C.Name;
因为要求只将代码以特定字母开头的产品的总计带到结果中,所以我不能在 Invoice 表上工作,而是在 InvoiceLines 表上工作。也因为还需要列出那些没有购买任何东西的客户,所以我想对 Customer 表使用 LEFT JOIN。
任何帮助,将不胜感激。
【问题讨论】:
-
意味深长示例数据和预期结果(最好是 DDL 和 DML 语句)将真正帮助我们帮助您。您的查询看起来根本不正确;特别是当你有 3 个
Invoice的实例时,它们都别名为I,并且一些范围是共享的。你也有一个GROUP BY但实际上并没有聚合任何该范围内的列,那么为什么要有GROUP BY呢? -
另外,当您需要列
Code时,为什么将LEFT JOIN更改为Customer必须有一个非NULL值?如果没有找到行,Code的值不可能是非NULL。 -
我正在尝试检索数据以分析每个客户特定商品的月销售额。部分分析还需要列出该月未进行任何购买的客户,因此我认为我可以通过 LEFT JOIN 实现这一点。我对 SQL 的了解非常有限,所以如果它没有任何意义,我深表歉意。所有 GROUP BY 语句都在那里,因为 SSMS 抱怨没有它们。
-
SUM(LI.LineTotal)甚至不起作用,您的查询中没有别名为LI的对象。 -
抱歉,应该是 IL。我已经更正了
标签: sql sql-server tsql