Langsung ke konten utama

CREATE CROSS TAB QUERY IN MYSQL

MySQL Multi-Aggregated Rows in Crosstab Queries

MySQL’s crosstabs contain aggregate functions on two or more fields, presented in a tabular format. In a multi-aggregate crosstab query, two different functions can be applied to the same field or the same function can be applied to multiple fields on the same (row or column) axis. Rob Gravelle shows you how to apply two different functions to the same field in order to create grouping levels in the row axis.
Today’s topic of discussion is crosstabs, which contain multiple aggregate functions in the row axis of a tabular resultset. Recall from the the All About the Crosstab Query article that an aggregate function is one that summarizes a group of related data in some way. Examples of aggregate functions include COUNT, SUM, AVG, MIN, and MAX. In a multi-aggregate crosstab query, two different functions can be applied to the same field or the same function can be applied to two or more fields. Today we’ll create a query that applies two different functions to the same field in order to create grouping levels in the row axis.

Recap of Crosstab Basics

In the Tips for Simplifying Crosstab Query Statements article, we took the complex SQL statement that we created in the All About the Crosstab Query article and simplified it to a more streamlined version:
SELECT CASE WHEN Month_Num IS NULL 
            THEN 'TOTAL' 
            ELSE Month 
       END      AS 'Month',
  REGION_1 AS 'REGION 1',  
  REGION_2 AS 'REGION 2',
  REGION_3 AS 'REGION 3',
  REGION_4 AS 'REGION 4',
  REGION_5 AS 'REGION 5',       
  TOTAL
FROM  (SELECT MONTH(CREATION_DATE)                          AS Month_Num,
     MONTHNAME(CREATION_DATE)                               AS Month,
     COUNT(CASE WHEN REGION_CODE ='01' THEN FEE_NUMBER END) AS REGION_1,
     COUNT(CASE WHEN REGION_CODE ='02' THEN FEE_NUMBER END) AS REGION_2,
     COUNT(CASE WHEN REGION_CODE ='03' THEN FEE_NUMBER END) AS REGION_3,
     COUNT(CASE WHEN REGION_CODE ='04' THEN FEE_NUMBER END) AS REGION_4,
     COUNT(CASE WHEN REGION_CODE ='05' THEN FEE_NUMBER END) AS REGION_5,
     COUNT(*)                                               AS TOTAL 
  FROM   TA_CASES
  WHERE  YEAR(CREATION_DATE)=1998
  GROUP BY Month_Num WITH ROLLUP) AS CA;
The subquery fetched all of the fields that we needed, plus the month number, for sorting.  We then selected from it by placing the code after the FROM of a second query. Performing a query in a two pass process in this way is called Pre (or Partial)-Aggregation. The first pass creates a derived table or resultset that performs most of the aggregation work, while the next pass does some formatting and any additional calculations that may be required.  The neccessitating of pre-aggregation here was the result of two factors: The ROLLUP GROUP BY modifier inserted a Null row into the resultset, which was difficult to replace with the “TOTAL” row header because of its late evaluation in the query process.  A second challenge was presented by the grouping on the output of date functions because grouping on the MONTHNAME() sorted the rows in alphabetical order, rather than chronological.
The above query produced the following desired crosstab, including chronological row sorting and totals:
MonthREGION 1REGION 2REGION 3REGION 4REGION 5TOTAL
April133376247171
May17552091143425
June8632211127420
July131042406123486
August181212749111533
September25160239288514
October9882952127521
November2862922120502
December11282326155522
TOTAL10683820783110414094

Multi-Aggregate Pivots

This query was not terribly complex as it only hit one table and pivoted between two fields: the Month and Region.  That’s called a Single Pivot.  If we wanted to breakdown the time periods further into other time periods, we would now be looking at a two-to-one pivot (eg: months and weeks per region).  On the column side, regions could likewise be broken down into specific cities, giving us a one-to-two pivot.  Adding the new fields to both the columns and rows would produce a true many-to-many multi-aggregate pivot.  The following chart illustrates the inherent complexety of multi-aggregate pivots:
ABC1C2Totalcolumn header 1
D1D2TotalD1D2Totalcolumn header 2
E1E2TotalE1E2TotalE1E2TotalE1E2Totalcolumn header 3
A1B1
B2
Totalrow sub total
A2B1
B2
Totalrow sub total
Totalrow total
row
header
1
row
header
2
col
sub
total
col
sub
total
col
sub
total
col
sub
total
col
sub
total
col
sub
total
col
total

Reporting on Two Row Fields

We’re going to create a Multi-Aggregate row crosstab by adding the Year to the row data, making it the new A row in the above diagram, thus displacing the months to the B field. That will allow us to report on multiple years, by calling the YEAR() function on the CREATION_DATE, much like we did for displaying the months. We’ll insert it as the first field in the SELECT list (new code appears in Red):
...
FROM  (SELECT YEAR(CREATION_DATE)              AS Year,
              MONTH(CREATION_DATE)             AS Month_Num,
              MONTHNAME(CREATION_DATE)         AS Month,
   ...
We can also easily include totals for each year by adding it to the GROUP BY clause:
       GROUP BY Year, Month_Num WITH ROLLUP) AS CA;
In addition to needing a column heading for the years, we also need to alter the months CASE statement, because rows which display the yearly totals will contain a NULL Month_num value:
SELECT CASE WHEN Year IS NULL
            THEN 'GRAND TOTAL' 
            ELSE Year 
       END      AS 'Year',
       CASE WHEN Month_Num IS NULL     
            THEN CASE WHEN Year IS NULL
                      THEN ''                                         
                      ELSE CONCAT(Year, ' TOTAL')                      
                 END
            ELSE Month 
       END      AS 'Month',  
  ...
Here then is the full SQL statement to include the Year rows.
SELECT CASE WHEN Year IS NULL
            THEN 'GRAND TOTAL' 
            ELSE Year 
       END      AS 'Year',
       CASE WHEN Month_Num IS NULL     
            THEN CASE WHEN Year IS NULL
                      THEN ''                                         
                      ELSE CONCAT(Year, ' TOTAL')                      
                 END
            ELSE Month 
       END      AS 'Month',  
       REGION_1 AS 'REGION 1',  
       REGION_2 AS 'REGION 2',
       REGION_3 AS 'REGION 3',
       REGION_4 AS 'REGION 4',
       REGION_5 AS 'REGION 5',       
       TOTAL
FROM  (SELECT YEAR(CREATION_DATE)                                    AS Year,
              MONTH(CREATION_DATE)                                   AS Month_Num,
              CONVERT(MONTHNAME(CREATION_DATE) USING latin1)         AS Month,
              COUNT(CASE WHEN REGION_CODE ='01' THEN FEE_NUMBER END) AS REGION_1,
              COUNT(CASE WHEN REGION_CODE ='02' THEN FEE_NUMBER END) AS REGION_2,
              COUNT(CASE WHEN REGION_CODE ='03' THEN FEE_NUMBER END) AS REGION_3,
              COUNT(CASE WHEN REGION_CODE ='04' THEN FEE_NUMBER END) AS REGION_4,
              COUNT(CASE WHEN REGION_CODE ='05' THEN FEE_NUMBER END) AS REGION_5,
              COUNT(*)                                               AS TOTAL 
       FROM   TA_CASES
       WHERE  YEAR(CREATION_DATE)>2003
       GROUP BY Year, Month_Num WITH ROLLUP) AS CA;
The revised SQL code produces the following result, which includes the YEAR headers in the first column, and the TOTAL summary row for each year:
YearMonthREGION 1REGION 2REGION 3REGION 4REGION 5TOTAL
2004January841156142248
2004February138140029212
2004March044115050209
2004April445119042210
2004May157151084294
2004June263142048259
2004July647110033199
2004August1038150153256
2004September345146734235
2004October255112034204
2004November436110143195
2004December130165031227
20042004 TOTAL425391616105232748
2005January334107234182
2005February024103015144
2005March130101024159
2005April327149027212
2005May136110027177
2005June352113028196
2005July138131322195
2005August451146136238
2005September952149049259
2005October1029100047186
2005November1111162018204
2005December466142019231
20052005 TOTAL50450151363462383
2006January268132030235
2006February14394024162
2006March330134029196
2006April147129021199
2006May1152124031220
2006June949126030214
2006July443125042217
2006August350132051241
2006September656149045262
2006October531121225184
2006November342146363258
2006December047115023194
20062006 TOTAL48558152754142582
2007January237152135229
2007February13586231156
2007March578132051268
2007April241125141211
2007May050122033206
2007June163107038209
2007July54165131150
2007August063110243219
2007September235134055227
2007October239120252225
2007November1022141036215
2007December512660017156
20072007 TOTAL81530135494632471
2008January152154149277
2008February01284134136
2008March03085127148
2008April32273040168
2008May04890229170
2008June1063122024225
2008July1938148328238
2008August5450105020230
2008September4234143244268
2008October7341112126253
2008November1115101020152
2008December28562160229541
20082008 TOTAL4984671377133702806
2009January68627123342882
2009February2987022120
2009March419106025154
2009April01095012117
2009May43193021151
2009June637194021251
2009July14292621165
2009August353116319195
2009September1122501149
2009December00101017
20092009 TOTAL764274832122042101
GRAND TOTAL 14832818821955232015091
Adding row fields is not all that difficult because queries naturally group data by rows. Therefore, all that is required is to add the new row to the SELECT and GROUP BY field lists and include a column for the row headers, as we did above. In the next installment, we will take on the more imposing challenge of adding a new column. It’s not as straighforward as might initially appear.
SOURCE: http://www.databasejournal.com/features/mysql/article.php/3865811/MySQL-Multi-Aggregated-Rows-in-Crosstab-Queries.htm
crosstab

Komentar

Postingan populer dari blog ini

Mengatasi "This app can’t run on your PC Windows 10"

  Salah satu pesan error yang sering muncul saat aplikasi tidak bisa dibuka di Windows 10 adalah “ This app can’t run on your PC ,   to find a version for your PC check with the software publisher “. Masalah seperti ini cukup umum dan dialami banyak orang, terutama saat menjalankan aplikasi yang bukan dari Microsoft. Penyebab utama terjadinya masalah ini adalah karena masalah kompatibilitas antara aplikasi dengan versi Windows yang dianggap tidak sesuai oleh sistem. Bisa juga karena aplikasi atau game yang akan jalankan tersebut terkena filter oleh Windows sehingga prosesnya diblokir. Windows 10 memiliki fitur untuk memblokir aplikasi tidak dikenal yang berasal dari  unverified developers , fitur ini secara default akan aktif dengan tujuan untuk mencegah masuknya aplikasi yang mengandung malware dan virus. Penyebab lainnya bisa juga karena file aplikasi yang rusak, file sistem yang korup, atau masalah yang disebabkan oleh malware dan virus. Pada kesempatan kali ini  ...

Linux Basic Command Cheat Sheet

 https://www.guru99.com/linux-commands-cheat-sheet.html Linux Command Cheat Sheet In this Linux/Unix command line cheat sheet, you will learn: Basic Linux commands File Permission commands Environment Variables command User management commands of linux Networking command Process command VI Editing Commands Basic Linux commands Command Description ls Lists all files and directories in the present working directory ls -R Lists files in sub-directories as well ls -a Lists hidden files as well ls -al Lists files and directories with detailed information like permissions,size, owner, etc. cd or cd ~ Navigate to HOME directory cd .. Move one level up cd To change to a particular directory cd / Move to the root directory cat > filename Creates a new file cat filename Displays the file content cat file1 file2 > file3 Joins two files (file1, file2) and stores the output in a new file (file3) mv file "new file path" Moves the files to the new location mv filename new_file_name Re...