SQL查询按月比较产品销量
我有一个每月状态数据库视图,我需要根据该视图构建报告。 视图中的数据如下所示:
Category | Revenue | Yearh | Month
Bikes 10 000 2008 1
Bikes 12 000 2008 2
Bikes 12 000 2008 3
Bikes 15 000 2008 1
Bikes 11 000 2007 2
Bikes 11 500 2007 3
Bikes 15 400 2007 4
...等等
该视图包含产品类别、收入、年份和月份。 我想创建一份比较 2007 年和 2008 年的报告,显示没有销售的月份为 0。 所以报告应该看起来像这样:
Category | Month | Rev. This Year | Rev. Last Year
Bikes 1 10 000 0
Bikes 2 12 000 11 000
Bikes 3 12 000 11 500
Bikes 4 0 15 400
需要注意的关键是第 1 个月仅在 2008 年有销售额,因此 2007 年为 0。此外,第 4 个月仅在 2008 年没有销售额,因此为 0,而它在 2007 年有销售额并且仍然显示。
另外,该报告实际上是针对财政年度的 - 因此,如果 2007 年或 2008 年的第 5 个月没有销售,我希望在两个列中都包含 0 的空列。
我得到的查询看起来像这样
SELECT
SP1.Program,
SP1.Year,
SP1.Month,
SP1.TotalRevenue,
IsNull(SP2.TotalRevenue, 0) AS LastYearTotalRevenue
FROM PVMonthlyStatusReport AS SP1
LEFT OUTER JOIN PVMonthlyStatusReport AS SP2 ON
SP1.Program = SP2.Program AND
SP2.Year = SP1.Year - 1 AND
SP1.Month = SP2.Month
WHERE
SP1.Program = 'Bikes' AND
SP1.Category = @Category AND
(SP1.Year >= @FinancialYear AND SP1.Year <= @FinancialYear + 1) AND
((SP1.Year = @FinancialYear AND SP1.Month > 6) OR
(SP1.Year = @FinancialYear + 1 AND SP1.Month <= 6))
ORDER BY SP1.Year, SP1.Month
:查询的一个问题是它不会返回上面示例数据中的第四行,因为我们在 2008 年没有任何销售,但我们实际上在 2007 年做了。
这可能是一个常见的查询/问题,但我的 SQL 执行后就生锈了前端开发这么久了。 任何帮助是极大的赞赏!
哦,顺便说一句,我正在使用 SQL 2005 进行此查询,因此如果有任何有用的新功能可能对我有帮助,请告诉我。
I have a Monthly Status database view I need to build a report based on. The data in the view looks something like this:
Category | Revenue | Yearh | Month
Bikes 10 000 2008 1
Bikes 12 000 2008 2
Bikes 12 000 2008 3
Bikes 15 000 2008 1
Bikes 11 000 2007 2
Bikes 11 500 2007 3
Bikes 15 400 2007 4
... And so forth
The view has a product category, a revenue, a year and a month. I want to create a report comparing 2007 and 2008, showing 0 for the months with no sales. So the report should look something like this:
Category | Month | Rev. This Year | Rev. Last Year
Bikes 1 10 000 0
Bikes 2 12 000 11 000
Bikes 3 12 000 11 500
Bikes 4 0 15 400
The key thing to notice is how month 1 only has sales in 2008, and therefore is 0 for 2007. Also, month 4 only has no sales in 2008, hence the 0, while it has sales in 2007 and still show up.
Also, the report is actually for financial year - so I would love to have empty columns with 0 in both if there was no sales in say month 5 for either 2007 or 2008.
The query I got looks something like this:
SELECT
SP1.Program,
SP1.Year,
SP1.Month,
SP1.TotalRevenue,
IsNull(SP2.TotalRevenue, 0) AS LastYearTotalRevenue
FROM PVMonthlyStatusReport AS SP1
LEFT OUTER JOIN PVMonthlyStatusReport AS SP2 ON
SP1.Program = SP2.Program AND
SP2.Year = SP1.Year - 1 AND
SP1.Month = SP2.Month
WHERE
SP1.Program = 'Bikes' AND
SP1.Category = @Category AND
(SP1.Year >= @FinancialYear AND SP1.Year <= @FinancialYear + 1) AND
((SP1.Year = @FinancialYear AND SP1.Month > 6) OR
(SP1.Year = @FinancialYear + 1 AND SP1.Month <= 6))
ORDER BY SP1.Year, SP1.Month
The problem with this query is that it would not return the fourth row in my example data above, since we didn't have any sales in 2008, but we actually did in 2007.
This is probably a common query/problem, but my SQL is rusty after doing front-end development for so long. Any help is greatly appreciated!
Oh, btw, I'm using SQL 2005 for this query so if there are any helpful new features that might help me let me know.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
Case 语句是我最好的 sql 朋友。 您还需要一个表格,列出在这两个月中产生 0 转速的时间。
假设基于下表的可用性:
和
没有空行的示例 1:
返回:
带有空行的示例 2:
我将使用子查询(但其他查询可能不会),并将为每个产品和年月组合返回一个空行。
返回:
请注意,大多数报告工具都会执行此交叉表或矩阵功能,现在我认为 SQL Server 2005 具有枢轴语法,也可以执行此操作。
这里有一些额外的资源。
案件
https://web.archive .org/web/20210728081626/https://www.4guysfromrolla.com/webtech/102704-1.shtml
SQL Server 2005 数据透视
http://msdn.microsoft.com/en-us/library/ms177410.aspx
The Case Statement is my best sql friend. You also need a table for time to generate your 0 rev in both months.
Assumptions are based on the availability of following tables:
and
Example 1 without empty rows:
RETURNS:
Example 2 with empty rows:
I am going to use a sub query (but others may not) and will return an empty row for every product and year month combo.
RETURNS:
Note that most reporting tools will do this crosstab or matrix functionality, and now that i think of it SQL Server 2005 has pivot syntax that will do this as well.
Here are some additional resources.
CASE
https://web.archive.org/web/20210728081626/https://www.4guysfromrolla.com/webtech/102704-1.shtml
SQL SERVER 2005 PIVOT
http://msdn.microsoft.com/en-us/library/ms177410.aspx
诀窍是执行 FULL JOIN,使用 ISNULL 从任一表中获取连接列。 我通常将其包装到视图或派生表中,否则您还需要在 WHERE 子句中使用 ISNULL。
这应该可以满足您的最低要求 - 2007 年或 2008 年或两者都有销售的行。 要获取任一年份都没有销售额的行,您只需内连接到 1-12 数字表(您执行 有其中之一,不是吗?)。
The trick is to do a FULL JOIN, with ISNULL's to get the joined columns from either table. I usually wrap this into a view or derived table, otherwise you need to use ISNULL in the WHERE clause as well.
That should get you your minimum requirements - rows with sales in either 2007 or 2008, or both. To get rows with no sales in either year, you just need to INNER JOIN to a 1-12 numbers table (you do have one of those, don't you?).
关于降价 - 是的,这令人沮丧。 编辑器确实预览了我的 HTML 表格,但发布后它就消失了 - 因此必须从帖子中删除所有 HTML 格式...
@kcrumley 我认为我们已经得出了类似的结论。 这个查询很容易变得非常难看。 实际上,在阅读您的答案之前,我使用类似(但不同的方法)解决了这个问题。 我有权在报告数据库上创建存储过程和函数。 我创建了一个表值函数,接受产品类别和财政年度作为参数。 在此基础上,该函数将填充一个包含 12 行的表。 如果有可用的销售,则行将使用视图中的数据填充,否则该行将具有 0 值。
然后,我连接函数返回的两个表。 因为我知道所有表都会有十二个漫游,所以分配更容易,并且我可以加入产品类别和月份:
我认为您的方法可能更干净一些,因为 GetFinancialYear 函数非常混乱! 但至少它有效 - 这让我现在很高兴;)
About the markdown - Yeah that is frustrating. The editor did preview my HTML table, but after posting it was gone - So had to remove all HTML formatting from the post...
@kcrumley I think we've reached similar conclusions. This query easily gets real ugly. I actually solved this before reading your answer, using a similar (but yet different approach). I have access to create stored procedures and functions on the reporting database. I created a Table Valued function accepting a product category and a financial year as the parameter. Based on that the function will populate a table containing 12 rows. The rows will be populated with data from the view if any sales available, if not the row will have 0 values.
I then join the two tables returned by the functions. Since I know all tables will have twelve roves it's allot easier, and I can join on Product Category and Month:
I think your approach is probably a little cleaner as the GetFinancialYear function is quite messy! But at least it works - which makes me happy for now ;)
我可能是错的,但您不应该使用完整的外连接而不是左连接吗? 这样您将从两个表中获得“空”列。
http://en.wikipedia.org/wiki/Join_(SQL)#Full_outer_join< /a>
I could be wrong but shouldn't you be using a full outer join instead of just a left join? That way you will be getting 'empty' columns from both tables.
http://en.wikipedia.org/wiki/Join_(SQL)#Full_outer_join
使用pivot和Dynamic Sql我们可以实现这个结果
结果
Using pivot and Dynamic Sql we can achieve this result
Result
@Christian——降价编辑器——呃; 特别是当你的帖子的预览和最终版本不一致时......
@Christian -- 完全外连接 -- 完全外连接被 WHERE 子句中引用 SP1 的事实所否决,并且 WHERE 子句在 JOIN 之后应用。 要对其中一个表进行过滤的完整外连接,您需要将 WHERE 子句放入子查询中,以便过滤发生在连接之前,或者尝试将所有 WHERE 条件构建到JOIN ON 子句,非常丑陋。 嗯,实际上没有什么好方法可以做到这一点。
@乔纳斯:考虑到这一点:
而且事实上,这项工作无法通过漂亮的查询来完成,我肯定会尝试获得您真正想要的结果。 进行丑陋的查询甚至无法获得您真正想要的确切数据是没有意义的。 ;)
所以,我建议分 5 个步骤进行:
1. 按照您希望结果匹配的格式创建临时表
2. 填充十二行,其中月份列为 1-12
3. 使用 SP1 逻辑更新“今年”列
4. 使用 SP2 逻辑更新“去年”列
5. 从临时表中选择
当然,我想我是假设您可以创建一个存储过程来完成此操作。 从技术上讲,您可能能够内联运行整个批次,但这种丑陋的情况很少见。 如果您无法创建 SP,我建议您通过子查询依靠完整的外部联接,但是当某一个月没有销售时,它不会为您带来一行。
@Christian -- markdown editor -- UGH; especially when the preview and the final version of your post disagree...
@Christian -- full outer join -- the full outer join is overruled by the fact that there are references to SP1 in the WHERE clause, and the WHERE clause is applied after the JOIN. To do a full outer join with filtering on one of the tables, you need to put your WHERE clause into a subquery, so the filtering happens before the join, or try to build all of your WHERE criteria onto the JOIN ON clause, which is insanely ugly. Well, there's actually no pretty way to do this one.
@Jonas: Considering this:
and the fact that this job can't be done with a pretty query, I would definitely try to get the results you actually want. No point in having an ugly query and not even getting the exact data you actually want. ;)
So, I'd suggest doing this in 5 steps:
1. create a temp table in the format you want your results to match
2. populate it with twelve rows, with 1-12 in the month column
3. update the "This Year" column using your SP1 logic
4. update the "Last Year" column using your SP2 logic
5. select from the temp table
Of course, I guess I'm working from the assumption that you can create a stored procedure to accomplish this. You might technically be able to run this whole batch inline, but that kind of ugliness is very rarely seen. If you can't make an SP, I suggest you fall back on the full outer join via subquery, but it won't get you a row when a month had no sales either year.