SQL query to compare product sales by month

后端 未结 6 1046
无人共我
无人共我 2021-02-10 07:52

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
B         


        
6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-10 08:17

    @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:

    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.

    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.

提交回复
热议问题