简体   繁体   中英

SQL query for 3-months data transformation

Let assume I have a record set like below:

ShopNo  Month   Year    ProfitPercentage
  S1     3      2011    25%
  S2     4      2011    35%
  S3     5      2011    36%

From the record, we can see shop 1 has only one record for the Month of 3 in 2011 and for other months we need to assume as 0% now we need to auto generate the data for other months too.

ShopNo  Month   Year    ProfitPercentage
   S1    1       2011      0%
   S1    2       2011      0%
   S1    3       2011      25%
   S1    4       2011      0%
   S1    5       2011      0%
   S1    6       2011      0%
   S1    7       2011      0%
   S1    8       2011      0%
   S1    9       2011      0%
   S1    10      2011      0%
   S1    11      2011      0%
   S1    12      2011      0%

Similarly need to generate for other shops too. On top of resultant data we need to do 3-months transformation:

  ShopNo    Month   Year    ProfitPercentage
     S1     1-3     2011    25%
     S1     2-4     2011    25%
     S1     3-5     2011    25%
     S1     4-6     2011    0%
     S1     5-7     2011    0%
     S1     6-8     2011    0%
     S1     7-9     2011    0%
     S1     8-10    2011    0%
     S1     9-11    2011    0%
     S1     10-12   2011    0%
     S1     11-1    2012    0%
     S1     12-2    2012    0%

Can anyone help me out to work out this !!!

You can cheat a little by hard coding the month/year matrix I don't think you can generate it without using some static values.

From there, it should be a short trip with GROUP BY with some / and % to get your 3 monthly round up.

WITH [Matrix] AS (
SELECT
  [Year].[Value] [Year],
  [Month].[Value] [Month]
FROM
  (SELECT 2011 [Value] UNION SELECT 2012 UNION SELECT 2013 UNION SELECT 2014) [Year]
  OUTER APPLY (SELECT 1 [Value] UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9 UNION SELECT 10 UNION SELECT 11 UNION SELECT 12) [Month]
)

SELECT
  M.[Year],
  M.[Month],
  ISNULL(X.[Percentage], 0)
FROM
  [Matrix] M
  LEFT OUTER JOIN (<your query goes here as a subquery>) X

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM