SlideShare ist ein Scribd-Unternehmen logo
1 von 22
Querying and Managing Data Using SQL Server 2005
Objectives


                In this session, you will learn to:
                   Use functions to customize the result set
                   Summarize and group data




     Ver. 1.0                        Session 3                 Slide 1 of 22
Querying and Managing Data Using SQL Server 2005
Using String Functions


                String functions:
                   Can be used to manipulate string values in the result set
                   Can only be used with char and varchar data types
                   Syntax:
                    SELECT function_name (parameters)
                Let’s see how…




     Ver. 1.0                        Session 3                            Slide 2 of 22
Querying and Managing Data Using SQL Server 2005
Using Date Functions


                Date functions:
                   Can be used to manipulate datetime values, perform arithmetic
                   operations, and perform date parsing
                Let’s see how…




     Ver. 1.0                       Session 3                           Slide 3 of 22
Querying and Managing Data Using SQL Server 2005
Using Mathematical Functions


                Mathematical functions:
                   Can be used to manipulate numeric values in a result set
                Let’s see how…




     Ver. 1.0                       Session 3                            Slide 4 of 22
Querying and Managing Data Using SQL Server 2005
Just a minute


                Identify the utility of the datepart function.




                Answer:
                    The datepart function is used to extract different parts
                    of a date value.



     Ver. 1.0                         Session 3                                Slide 5 of 22
Querying and Managing Data Using SQL Server 2005
Just a minute


                The management of AdventureWorks wants to increase the
                shift time from 8 hours to 10 hours. Calculate the end time
                of the shifts based on their start time.




                Answer:
                   SELECT ShiftID, StartTime, 'EndTime' =
                   dateadd(hh, 10, StartTime) FROM
                   HumanResources.Shift


     Ver. 1.0                      Session 3                        Slide 6 of 22
Querying and Managing Data Using SQL Server 2005
Using Ranking Functions


                Ranking functions:
                   Can be used to generate sequential numbers for each row or
                   to give a rank based on specific criteria
                   Supported by SQL Server are:
                      row_number
                      rank
                      dense_rank
                Let’s see how…




     Ver. 1.0                        Session 3                         Slide 7 of 22
Querying and Managing Data Using SQL Server 2005
Using System Functions


                System functions:
                   Can be used to query system tables
                   Commonly used in SQL Server are:
                    • host_id
                    • host_name
                    • suser_id
                Let’s see how…




     Ver. 1.0                       Session 3           Slide 8 of 22
Querying and Managing Data Using SQL Server 2005
Demo: Customizing the Result Set


                Problem Statement:
                   The management at AdventureWorks, Inc. wants to view a
                   report that displays the employee ID, designation, and age of
                   the employees who are working as a marketing manager or a
                   marketing specialist. The data should be displayed in
                   uppercase.
                   The employee details are stored in the Employee table in the
                   AdventureWorks database. How will you display the required
                   data?




     Ver. 1.0                       Session 3                            Slide 9 of 22
Querying and Managing Data Using SQL Server 2005
Demo: Customizing the Result Set (Contd.)


                Solution:
                   To solve the preceding problem, you need to perform the
                   following tasks:
                     1. Create a query.
                     2. Execute the query to display data.




     Ver. 1.0                          Session 3                        Slide 10 of 22
Querying and Managing Data Using SQL Server 2005
Summarizing Data by Using Aggregate Functions


                Aggregate functions:
                – Can be used to summarize values of a column based on a set
                  of rows
                – Supported by SQL Server are:
                      avg
                      count
                      min
                      max
                      sum
                Let’s see how…




     Ver. 1.0                      Session 3                         Slide 11 of 22
Querying and Managing Data Using SQL Server 2005
Just a minute


                What would be the output of the following query?
                SELECT 'Maximum Rate' = max (UnitPrice) FROM
                Sales.SalesOrderDetail




                Answer:
                – The query displays the maximum unit price from the
                  SalesOrderDetail table.



     Ver. 1.0                      Session 3                           Slide 12 of 22
Querying and Managing Data Using SQL Server 2005
Grouping Data


               • Data is grouped to generate summarized reports.
               • Clauses used to group data are:
                     GROUP BY
                     COMPUTE
                     COMPUTE BY
                     PIVOT




    Ver. 1.0                        Session 3                      Slide 13 of 22
Querying and Managing Data Using SQL Server 2005
Grouping Data (Contd.)


                GROUP BY:
                   Summarizes the result set into groups as defined in the query
                   by using aggregate functions
                   Uses the HAVING clause to eliminate all those groups that do
                   not match the condition
                   Syntax:
                    SELECT column_list
                    FROM table_name
                    WHERE condition
                    [GROUP BY [ALL] expression [, expression]
                    [HAVING search_condition]
                Let’s see how…




     Ver. 1.0                       Session 3                            Slide 14 of 22
Querying and Managing Data Using SQL Server 2005
Grouping Data (Contd.)


                COMPUTE:
                  Can be used to generate summary rows by using aggregate
                  functions
                COMPUTE BY:
                  Can be used to calculate summary values of the result set on a
                  group of data
                  The column on which the data is to be grouped is mentioned
                  after the BY keyword.




     Ver. 1.0                      Session 3                           Slide 15 of 22
Querying and Managing Data Using SQL Server 2005
Grouping Data (Contd.)


                   Syntax:
                    SELECT column_list
                    FROM table_name
                    ORDER BY column_name
                    COMPUTE aggregate_function (column_name)
                    [, aggregate_function (column_name)...]
                    [BY column_name [, column_name]...]
                Let’s see how…




     Ver. 1.0                    Session 3                 Slide 16 of 22
Querying and Managing Data Using SQL Server 2005
Grouping Data (Contd.)


                PIVOT:
                   Is used to transform a set of columns into values
                   Syntax:
                     SELECT * FROM table_name
                     PIVOT (aggregation_function (value_column)
                     FOR pivot_column
                     IN (column_list)
                     ) table_alias
                Let’s see how…




     Ver. 1.0                     Session 3                     Slide 17 of 22
Querying and Managing Data Using SQL Server 2005
Just a minute


                When grouping data, which of the following clauses helps
                eliminate the groups that do not match the condition
                specified?
                1.   NOT IN
                2.   HAVING
                3.   WHERE
                4.   COMPUTE




                Answer:
                 2. HAVING




     Ver. 1.0                      Session 3                       Slide 18 of 22
Querying and Managing Data Using SQL Server 2005
Just a minute


                Match the column A and with column B.
                    Column A   Column B

                    ALL        Used by aggregate functions
                    PIVOT      Returns zero or more values
                    IN         Used for modifying comparison
                               operator
                    >          Relational Operator




                Answer:
                    Column A   Column B

                    ALL        Used for modifying comparison
                               operator
                    PIVOT      Relational Operator
                    IN         Returns zero or more values
                    >          Used by aggregate functions

     Ver. 1.0                          Session 3               Slide 19 of 22
Querying and Managing Data Using SQL Server 2005
Demo: Summarizing and Grouping Data


               Problem Statement:
                  You are a database developer of AdventureWorks, Inc. The
                  management wants to view the average quantity ordered for
                  each product group. The data should be displayed in the
                  descending order of ProductID.
                  The sales details are stored in the SalesOrderHeader and
                  SalesOrderDetails tables in the AdventureWorks database.
                  How will you generate this report?




    Ver. 1.0                       Session 3                         Slide 20 of 22
Querying and Managing Data Using SQL Server 2005
Demo: Summarizing and Grouping Data (Contd.)


                Solution:
                   To solve the preceding problem, you need to perform the
                   following tasks:
                     1. Create a query.
                     2. Execute the query to verify the result.




     Ver. 1.0                           Session 3                       Slide 21 of 22
Querying and Managing Data Using SQL Server 2005
Summary


               In this session, you learned that:
                – The string functions are used to format data in the result set.
                – The date functions are used to manipulate date values.
                – The mathematical functions are used to perform numerical
                  operations.
                – The ranking functions are used to generate sequential
                  numbers for each row or to give a rank based on specific
                  criteria.
                – The system functions are used to query system tables.
                – The aggregate functions, such as avg, count, min, max, and
                  sum are used to retrieve summarized data.
                – The GROUP BY and PIVOT clauses are used to group the
                  result set.
                – The COMPUTE and COMPUTE BY clauses are used to
                  calculate summarized values in a grouped result set.

    Ver. 1.0                        Session 3                            Slide 22 of 22

Weitere ähnliche Inhalte

Andere mochten auch

Grafico diario del dax perfomance index para el 15 06-2012
Grafico diario del dax perfomance index para el 15 06-2012Grafico diario del dax perfomance index para el 15 06-2012
Grafico diario del dax perfomance index para el 15 06-2012Experiencia Trading
 
DrupalCamp Campinas 2016 - Auditando performance, conteúdo e boas práticas em...
DrupalCamp Campinas 2016 - Auditando performance, conteúdo e boas práticas em...DrupalCamp Campinas 2016 - Auditando performance, conteúdo e boas práticas em...
DrupalCamp Campinas 2016 - Auditando performance, conteúdo e boas práticas em...Erick Bonnemasou Jaccoud
 
Diapositivas yurbis
Diapositivas yurbisDiapositivas yurbis
Diapositivas yurbisyurbisveliz
 
Internacionalización de marcas (Resumen tomado del libro: Administración Estr...
Internacionalización de marcas (Resumen tomado del libro: Administración Estr...Internacionalización de marcas (Resumen tomado del libro: Administración Estr...
Internacionalización de marcas (Resumen tomado del libro: Administración Estr...NilssonRivas
 
eCommerce internacional: 20 claves para crecer.
eCommerce internacional: 20 claves para crecer. eCommerce internacional: 20 claves para crecer.
eCommerce internacional: 20 claves para crecer. Carmen Urbano
 
Serenity sky affrètement congo
Serenity sky affrètement congoSerenity sky affrètement congo
Serenity sky affrètement congoFabrice Lambion
 

Andere mochten auch (12)

Grafico diario del dax perfomance index para el 15 06-2012
Grafico diario del dax perfomance index para el 15 06-2012Grafico diario del dax perfomance index para el 15 06-2012
Grafico diario del dax perfomance index para el 15 06-2012
 
Ds 7
Ds 7Ds 7
Ds 7
 
Apokalipsa już niebawem
Apokalipsa już niebawemApokalipsa już niebawem
Apokalipsa już niebawem
 
Informe de Comite de Reasentamiento julio agosto de 2015
Informe de Comite de Reasentamiento julio agosto de 2015Informe de Comite de Reasentamiento julio agosto de 2015
Informe de Comite de Reasentamiento julio agosto de 2015
 
DrupalCamp Campinas 2016 - Auditando performance, conteúdo e boas práticas em...
DrupalCamp Campinas 2016 - Auditando performance, conteúdo e boas práticas em...DrupalCamp Campinas 2016 - Auditando performance, conteúdo e boas práticas em...
DrupalCamp Campinas 2016 - Auditando performance, conteúdo e boas práticas em...
 
Como empezó todo.odp
Como empezó todo.odpComo empezó todo.odp
Como empezó todo.odp
 
Diapositivas yurbis
Diapositivas yurbisDiapositivas yurbis
Diapositivas yurbis
 
Dany
DanyDany
Dany
 
2010 02 SEO Business Rodrigo Miranda Mib
2010 02 SEO Business Rodrigo Miranda Mib2010 02 SEO Business Rodrigo Miranda Mib
2010 02 SEO Business Rodrigo Miranda Mib
 
Internacionalización de marcas (Resumen tomado del libro: Administración Estr...
Internacionalización de marcas (Resumen tomado del libro: Administración Estr...Internacionalización de marcas (Resumen tomado del libro: Administración Estr...
Internacionalización de marcas (Resumen tomado del libro: Administración Estr...
 
eCommerce internacional: 20 claves para crecer.
eCommerce internacional: 20 claves para crecer. eCommerce internacional: 20 claves para crecer.
eCommerce internacional: 20 claves para crecer.
 
Serenity sky affrètement congo
Serenity sky affrètement congoSerenity sky affrètement congo
Serenity sky affrètement congo
 

Ähnlich wie 03 qmds2005 session03

11 qmds2005 session16
11 qmds2005 session1611 qmds2005 session16
11 qmds2005 session16Niit Care
 
01 qmds2005 session01
01 qmds2005 session0101 qmds2005 session01
01 qmds2005 session01Niit Care
 
07 qmds2005 session10
07 qmds2005 session1007 qmds2005 session10
07 qmds2005 session10Niit Care
 
10 qmds2005 session14
10 qmds2005 session1410 qmds2005 session14
10 qmds2005 session14Niit Care
 
Getting Started with MySQL II
Getting Started with MySQL IIGetting Started with MySQL II
Getting Started with MySQL IISankhya_Analytics
 
New features of sql server 2005
New features of sql server 2005New features of sql server 2005
New features of sql server 2005Govind Raj
 
Introduction to Threading in .Net
Introduction to Threading in .NetIntroduction to Threading in .Net
Introduction to Threading in .Netwebhostingguy
 
An introduction to new data warehouse scalability features in sql server 2008
An introduction to new data warehouse scalability features in sql server 2008An introduction to new data warehouse scalability features in sql server 2008
An introduction to new data warehouse scalability features in sql server 2008Klaudiia Jacome
 
Ms sql server architecture
Ms sql server architectureMs sql server architecture
Ms sql server architectureAjeet Singh
 
Sql server ___________session 1(sql 2008)
Sql server  ___________session 1(sql 2008)Sql server  ___________session 1(sql 2008)
Sql server ___________session 1(sql 2008)Ehtisham Ali
 
MySQL 8 -- A new beginning : Sunshine PHP/PHP UK (updated)
MySQL 8 -- A new beginning : Sunshine PHP/PHP UK (updated)MySQL 8 -- A new beginning : Sunshine PHP/PHP UK (updated)
MySQL 8 -- A new beginning : Sunshine PHP/PHP UK (updated)Dave Stokes
 
Session 2: SQL Server 2012 with Christian Malbeuf
Session 2: SQL Server 2012 with Christian MalbeufSession 2: SQL Server 2012 with Christian Malbeuf
Session 2: SQL Server 2012 with Christian MalbeufCTE Solutions Inc.
 
Query parameterization
Query parameterizationQuery parameterization
Query parameterizationRiteshkiit
 
SQL Server 2000 Research Series - Architecture Overview
SQL Server 2000 Research Series - Architecture OverviewSQL Server 2000 Research Series - Architecture Overview
SQL Server 2000 Research Series - Architecture OverviewJerry Yang
 
SQL SERVER 2008 R2 CTP
SQL SERVER 2008 R2 CTPSQL SERVER 2008 R2 CTP
SQL SERVER 2008 R2 CTPGovind S Yadav
 
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...Jürgen Ambrosi
 

Ähnlich wie 03 qmds2005 session03 (20)

11 qmds2005 session16
11 qmds2005 session1611 qmds2005 session16
11 qmds2005 session16
 
01 qmds2005 session01
01 qmds2005 session0101 qmds2005 session01
01 qmds2005 session01
 
07 qmds2005 session10
07 qmds2005 session1007 qmds2005 session10
07 qmds2005 session10
 
10 qmds2005 session14
10 qmds2005 session1410 qmds2005 session14
10 qmds2005 session14
 
Getting Started with MySQL II
Getting Started with MySQL IIGetting Started with MySQL II
Getting Started with MySQL II
 
New features of sql server 2005
New features of sql server 2005New features of sql server 2005
New features of sql server 2005
 
Introduction to Threading in .Net
Introduction to Threading in .NetIntroduction to Threading in .Net
Introduction to Threading in .Net
 
An introduction to new data warehouse scalability features in sql server 2008
An introduction to new data warehouse scalability features in sql server 2008An introduction to new data warehouse scalability features in sql server 2008
An introduction to new data warehouse scalability features in sql server 2008
 
6232 b 04
6232 b 046232 b 04
6232 b 04
 
Ms sql server architecture
Ms sql server architectureMs sql server architecture
Ms sql server architecture
 
Sql server ___________session 1(sql 2008)
Sql server  ___________session 1(sql 2008)Sql server  ___________session 1(sql 2008)
Sql server ___________session 1(sql 2008)
 
MySQL 8 -- A new beginning : Sunshine PHP/PHP UK (updated)
MySQL 8 -- A new beginning : Sunshine PHP/PHP UK (updated)MySQL 8 -- A new beginning : Sunshine PHP/PHP UK (updated)
MySQL 8 -- A new beginning : Sunshine PHP/PHP UK (updated)
 
SQL Tunning
SQL TunningSQL Tunning
SQL Tunning
 
Session 2: SQL Server 2012 with Christian Malbeuf
Session 2: SQL Server 2012 with Christian MalbeufSession 2: SQL Server 2012 with Christian Malbeuf
Session 2: SQL Server 2012 with Christian Malbeuf
 
Query parameterization
Query parameterizationQuery parameterization
Query parameterization
 
Using T-SQL
Using T-SQL Using T-SQL
Using T-SQL
 
SQL Server 2000 Research Series - Architecture Overview
SQL Server 2000 Research Series - Architecture OverviewSQL Server 2000 Research Series - Architecture Overview
SQL Server 2000 Research Series - Architecture Overview
 
Oracle SQL Training in Chennai, Tambaram
Oracle SQL Training in Chennai, TambaramOracle SQL Training in Chennai, Tambaram
Oracle SQL Training in Chennai, Tambaram
 
SQL SERVER 2008 R2 CTP
SQL SERVER 2008 R2 CTPSQL SERVER 2008 R2 CTP
SQL SERVER 2008 R2 CTP
 
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
 

Mehr von Niit Care (20)

Ajs 1 b
Ajs 1 bAjs 1 b
Ajs 1 b
 
Ajs 4 b
Ajs 4 bAjs 4 b
Ajs 4 b
 
Ajs 4 a
Ajs 4 aAjs 4 a
Ajs 4 a
 
Ajs 4 c
Ajs 4 cAjs 4 c
Ajs 4 c
 
Ajs 3 b
Ajs 3 bAjs 3 b
Ajs 3 b
 
Ajs 3 a
Ajs 3 aAjs 3 a
Ajs 3 a
 
Ajs 3 c
Ajs 3 cAjs 3 c
Ajs 3 c
 
Ajs 2 b
Ajs 2 bAjs 2 b
Ajs 2 b
 
Ajs 2 a
Ajs 2 aAjs 2 a
Ajs 2 a
 
Ajs 2 c
Ajs 2 cAjs 2 c
Ajs 2 c
 
Ajs 1 a
Ajs 1 aAjs 1 a
Ajs 1 a
 
Ajs 1 c
Ajs 1 cAjs 1 c
Ajs 1 c
 
Dacj 4 2-c
Dacj 4 2-cDacj 4 2-c
Dacj 4 2-c
 
Dacj 4 2-b
Dacj 4 2-bDacj 4 2-b
Dacj 4 2-b
 
Dacj 4 2-a
Dacj 4 2-aDacj 4 2-a
Dacj 4 2-a
 
Dacj 4 1-c
Dacj 4 1-cDacj 4 1-c
Dacj 4 1-c
 
Dacj 4 1-b
Dacj 4 1-bDacj 4 1-b
Dacj 4 1-b
 
Dacj 4 1-a
Dacj 4 1-aDacj 4 1-a
Dacj 4 1-a
 
Dacj 1-2 b
Dacj 1-2 bDacj 1-2 b
Dacj 1-2 b
 
Dacj 1-3 c
Dacj 1-3 cDacj 1-3 c
Dacj 1-3 c
 

Kürzlich hochgeladen

The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 

Kürzlich hochgeladen (20)

The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 

03 qmds2005 session03

  • 1. Querying and Managing Data Using SQL Server 2005 Objectives In this session, you will learn to: Use functions to customize the result set Summarize and group data Ver. 1.0 Session 3 Slide 1 of 22
  • 2. Querying and Managing Data Using SQL Server 2005 Using String Functions String functions: Can be used to manipulate string values in the result set Can only be used with char and varchar data types Syntax: SELECT function_name (parameters) Let’s see how… Ver. 1.0 Session 3 Slide 2 of 22
  • 3. Querying and Managing Data Using SQL Server 2005 Using Date Functions Date functions: Can be used to manipulate datetime values, perform arithmetic operations, and perform date parsing Let’s see how… Ver. 1.0 Session 3 Slide 3 of 22
  • 4. Querying and Managing Data Using SQL Server 2005 Using Mathematical Functions Mathematical functions: Can be used to manipulate numeric values in a result set Let’s see how… Ver. 1.0 Session 3 Slide 4 of 22
  • 5. Querying and Managing Data Using SQL Server 2005 Just a minute Identify the utility of the datepart function. Answer: The datepart function is used to extract different parts of a date value. Ver. 1.0 Session 3 Slide 5 of 22
  • 6. Querying and Managing Data Using SQL Server 2005 Just a minute The management of AdventureWorks wants to increase the shift time from 8 hours to 10 hours. Calculate the end time of the shifts based on their start time. Answer: SELECT ShiftID, StartTime, 'EndTime' = dateadd(hh, 10, StartTime) FROM HumanResources.Shift Ver. 1.0 Session 3 Slide 6 of 22
  • 7. Querying and Managing Data Using SQL Server 2005 Using Ranking Functions Ranking functions: Can be used to generate sequential numbers for each row or to give a rank based on specific criteria Supported by SQL Server are: row_number rank dense_rank Let’s see how… Ver. 1.0 Session 3 Slide 7 of 22
  • 8. Querying and Managing Data Using SQL Server 2005 Using System Functions System functions: Can be used to query system tables Commonly used in SQL Server are: • host_id • host_name • suser_id Let’s see how… Ver. 1.0 Session 3 Slide 8 of 22
  • 9. Querying and Managing Data Using SQL Server 2005 Demo: Customizing the Result Set Problem Statement: The management at AdventureWorks, Inc. wants to view a report that displays the employee ID, designation, and age of the employees who are working as a marketing manager or a marketing specialist. The data should be displayed in uppercase. The employee details are stored in the Employee table in the AdventureWorks database. How will you display the required data? Ver. 1.0 Session 3 Slide 9 of 22
  • 10. Querying and Managing Data Using SQL Server 2005 Demo: Customizing the Result Set (Contd.) Solution: To solve the preceding problem, you need to perform the following tasks: 1. Create a query. 2. Execute the query to display data. Ver. 1.0 Session 3 Slide 10 of 22
  • 11. Querying and Managing Data Using SQL Server 2005 Summarizing Data by Using Aggregate Functions Aggregate functions: – Can be used to summarize values of a column based on a set of rows – Supported by SQL Server are: avg count min max sum Let’s see how… Ver. 1.0 Session 3 Slide 11 of 22
  • 12. Querying and Managing Data Using SQL Server 2005 Just a minute What would be the output of the following query? SELECT 'Maximum Rate' = max (UnitPrice) FROM Sales.SalesOrderDetail Answer: – The query displays the maximum unit price from the SalesOrderDetail table. Ver. 1.0 Session 3 Slide 12 of 22
  • 13. Querying and Managing Data Using SQL Server 2005 Grouping Data • Data is grouped to generate summarized reports. • Clauses used to group data are: GROUP BY COMPUTE COMPUTE BY PIVOT Ver. 1.0 Session 3 Slide 13 of 22
  • 14. Querying and Managing Data Using SQL Server 2005 Grouping Data (Contd.) GROUP BY: Summarizes the result set into groups as defined in the query by using aggregate functions Uses the HAVING clause to eliminate all those groups that do not match the condition Syntax: SELECT column_list FROM table_name WHERE condition [GROUP BY [ALL] expression [, expression] [HAVING search_condition] Let’s see how… Ver. 1.0 Session 3 Slide 14 of 22
  • 15. Querying and Managing Data Using SQL Server 2005 Grouping Data (Contd.) COMPUTE: Can be used to generate summary rows by using aggregate functions COMPUTE BY: Can be used to calculate summary values of the result set on a group of data The column on which the data is to be grouped is mentioned after the BY keyword. Ver. 1.0 Session 3 Slide 15 of 22
  • 16. Querying and Managing Data Using SQL Server 2005 Grouping Data (Contd.) Syntax: SELECT column_list FROM table_name ORDER BY column_name COMPUTE aggregate_function (column_name) [, aggregate_function (column_name)...] [BY column_name [, column_name]...] Let’s see how… Ver. 1.0 Session 3 Slide 16 of 22
  • 17. Querying and Managing Data Using SQL Server 2005 Grouping Data (Contd.) PIVOT: Is used to transform a set of columns into values Syntax: SELECT * FROM table_name PIVOT (aggregation_function (value_column) FOR pivot_column IN (column_list) ) table_alias Let’s see how… Ver. 1.0 Session 3 Slide 17 of 22
  • 18. Querying and Managing Data Using SQL Server 2005 Just a minute When grouping data, which of the following clauses helps eliminate the groups that do not match the condition specified? 1. NOT IN 2. HAVING 3. WHERE 4. COMPUTE Answer: 2. HAVING Ver. 1.0 Session 3 Slide 18 of 22
  • 19. Querying and Managing Data Using SQL Server 2005 Just a minute Match the column A and with column B. Column A Column B ALL Used by aggregate functions PIVOT Returns zero or more values IN Used for modifying comparison operator > Relational Operator Answer: Column A Column B ALL Used for modifying comparison operator PIVOT Relational Operator IN Returns zero or more values > Used by aggregate functions Ver. 1.0 Session 3 Slide 19 of 22
  • 20. Querying and Managing Data Using SQL Server 2005 Demo: Summarizing and Grouping Data Problem Statement: You are a database developer of AdventureWorks, Inc. The management wants to view the average quantity ordered for each product group. The data should be displayed in the descending order of ProductID. The sales details are stored in the SalesOrderHeader and SalesOrderDetails tables in the AdventureWorks database. How will you generate this report? Ver. 1.0 Session 3 Slide 20 of 22
  • 21. Querying and Managing Data Using SQL Server 2005 Demo: Summarizing and Grouping Data (Contd.) Solution: To solve the preceding problem, you need to perform the following tasks: 1. Create a query. 2. Execute the query to verify the result. Ver. 1.0 Session 3 Slide 21 of 22
  • 22. Querying and Managing Data Using SQL Server 2005 Summary In this session, you learned that: – The string functions are used to format data in the result set. – The date functions are used to manipulate date values. – The mathematical functions are used to perform numerical operations. – The ranking functions are used to generate sequential numbers for each row or to give a rank based on specific criteria. – The system functions are used to query system tables. – The aggregate functions, such as avg, count, min, max, and sum are used to retrieve summarized data. – The GROUP BY and PIVOT clauses are used to group the result set. – The COMPUTE and COMPUTE BY clauses are used to calculate summarized values in a grouped result set. Ver. 1.0 Session 3 Slide 22 of 22

Hinweis der Redaktion

  1. Begin by sharing the objectives of the session with the students. In this session, you will explain to the students to use various system-defined functions provided by SQL Server 2005. In addition, you will teach them how to summarize and group data. You may begin the session by stating the need for various system-defined functions. Further you can state that SQL Server 2005 provides the database developer with various system-defined functions. These functions can be used to format the data returned by a query.
  2. In this topic, you will explain the usage of various string functions, to the students. You can state that string functions are used to perform various string operations on the data returned by a query. Explain to the students that string functions can work only with char and varchar data types. Ask the students to refer to the Student Guide for various string functions. You can use the examples given in the Student Guide to clarify the concept to the students. Additional Input You can use the CONVERT function to convert an expression into another data type. The CONVERT function enables quick conversion of system and object information without writing several queries. The syntax of the CONVERT function is: CONVERT (datatype [(length)], expression [, style]) where, datatype is the system-defined data type. (User-defined data types cannot be used). length is the optional parameter of char, varchar, or binary data types. expression is any valid expression to be converted from one data type to another. style is the method of representing the date while converting the date data type into the character data type.
  3. In this topic, you need to explain the concept and usage of the date functions. Inform the students that many a time they need to perform a number of manipulations on the data stored in the date format within a table. In addition, explain that datepart is the parameter that describes the part of the date on which the function will be performed, such as month or year. Ask the students to refer to the Student Guide for a list of date functions and date parts. You can use the examples given in the Student Guide to clarify the concept to the students.
  4. In this topic, you need to explain the concept of the mathematical functions. Ask the students to refer to Student Guide for the list of mathematical functions. You can use the examples given in the Student Guide to clarify the concept to the students.
  5. Reiterate the concepts taught earlier by asking the given question.
  6. Reiterate the concepts taught earlier by asking the given question.
  7. In this topic, you need to explain the concept of the ranking functions. Ensure that the concepts are clear to the students before presenting the demo. You can use the examples given in the Student Guide to clarify the concept to the students. Additional Input:
  8. Example: (displays terminal id) SELECT HOST_ID() Inform the students: CG Input Converting an expression You can use the CONVERT function to convert an expression into another data type. The CONVERT function enables quick conversion of system and object information without writing several queries. The syntax of the CONVERT function is: CONVERT (datatype [(length)], expression [, style]) where, datatype is the system-defined data type. (User-defined data types cannot be used). length is the optional parameter of char, varchar, or binary data types. expression is any valid expression to be converted from one data type to another. style is the method of representing the date when converting the date data type into the character data type Consider the following example, in which you need to retrieve the data of the VacationHours column from the Employee table, by converting the data into a character data type. SELECT VacationHours = CONVERT(char(10), VacationHours)FROM HumanResources.Employee The CONVERT function is used to change data from one type to another. This function is required when the SQL Server cannot convert the data implicitly. The style values are used with the CONVERT function to specify the date format when data is converted between character and date data type. SQL Server 2005 provides the following style values that can be used to change the date format. Without century (yy)Input/Output 0 or 100mon dd yyyy hh:mm (AM or PM)1mm/dd/yy2yy.mm.dd3dd/mm/yy4dd.mm.yy5dd-mm-yy101mm/dd/yyyy102yyyy.mm.dd103dd/mm/yyyy104dd.mm.yyyy105dd-mm-yyyy StyleValues of the Date Format Compare the style values and observe that when the styles used are 1, 2, 3, 4, or 5, year is displayed in the yy format. Similarly, when the styles used are 101, 102, 103, 104, or 105, year is displayed in the yyyy format. Consider the following example, where you need to display the title and hire date from the Employee table. The hire date is converted from the date data type to the character data type and then displayed in the yy.mm.dd format. This is because the style specified in the function is 2. SELECT Title, CONVERT(char(10),HireDate,2) FROM HumanResources.Employee Note Like CONVERT, CAST also provides the same functionality.
  9. Aggregate Functions Tell the students that aggregate functions are used to count or to find out the average of a particular column. In addition also tell the students that these should only be used on numeric columns. Besides, when an aggregate function is used on a column, NULL values are not considered. Additional Inputs MAX and MIN functions cannot be used on the bit data type columns. Example: (AVG) SELECT 'Average Rate' = AVG (Rate) FROM HumanResources.EmployeePayHistory Example: (COUNT) SELECT 'Unique Rate' = COUNT (DISTINCT Rate) FROM HumanResources.EmployeePayHistory Example: (MIN) SELECT 'Minimum Rate' = MIN (Rate) FROM HumanResources.EmployeePayHistory Example: (MAX) SELECT 'Maximum Rate' = MAX (Rate) FROM HumanResources.EmployeePayHistory Example: (SUM) SELECT 'Sum' = SUM (DISTINCT Rate) FROM HumanResources.EmployeePayHistory
  10. GROUP BY Clause Tell the students that the GROUP BY clause is used to group the output of the SELECT statement in several groups. If ALL is used, then it ignores the restriction provided by the WHERE clause. Just like the WHERE clause, you can use the HAVING clause with the GROUP BY clause. Example: (GROUP BY) SELECT Title, Minimum = MIN(VacationHours), Maximum = MAX(VacationHours) FROM HumanResources.Employee WHERE VacationHours > 20 GROUP BY Title Example: (HAVING) SELECT Title, 'Average Vacation Hours' = AVG(VacationHours) FROM HumanResources.Employee WHERE VacationHours > 30 GROUP BY Title HAVING AVG(VacationHours) >55 Additional Inputs All columns mentioned in the GROUP BY clause have to be included in the SELECT list. If a WHERE clause is present, then the GROUP BY clause groups only those rows which are satisfied by the conditions used in the WHERE clause.
  11. COMPUTE BY clause Stress that the COMPUTE BY clause is used to generate totals and subtotals in a control break report. Additional Inputs The columns that are mentioned in the COMPUTE clause need to be part of the SELECT list. Use an ORDER BY clause with the COMPUTE BY clause so that rows are grouped together.
  12. Example SELECT Title, 'Average VacationHours' = VacationHours, 'Average SickLeaveHours' = SickLeaveHours FROM HumanResources.Employee WHERE Title IN ('Recruiter', 'Stocker') ORDER BY Title, VacationHours, SickLeaveHours COMPUTE AVG(VacationHours), AVG(SickLeaveHours) BY Title Example SELECT Title, 'Total VacationHours' = VacationHours, 'Total SickLeaveHours' = SickLeaveHours FROM HumanResources.Employee WHERE Title IN ('Recruiter', 'Stocker')ORDER BY Title, VacationHours, SickLeaveHours COMPUTE SUM(VacationHours), SUM(SickLeaveHours) BY Title COMPUTE SUM(VacationHours), SUM(SickLeaveHours)
  13. Example: SELECT DepartmentID, [3] AS 'Manager 1', [109] AS 'Manager 2', [148] AS 'Manager 3' FROM (SELECT a.DepartmentID, b.EmployeeID, b.ManagerID FROM HumanResources.Department AS a JOIN HumanResources.EmployeeDepartmentHistory AS c ON a.DepartmentID = c.DepartmentID JOIN HumanResources.Employee AS b ON c.EmployeeID = b.EmployeeID WHERE c.Enddate IS NULL) p PIVOT ( COUNT(EmployeeID) FOR ManagerID IN ([3],[109],[148] ) )AS PVT
  14. You can summarize the session by running through the summary given in SG. In addition, you can also ask students summarize what they have learnt in this session.