Home Database Mysql Tutorial SQLSERVER中union,cube,rollup,cumpute运算符使用说明

SQLSERVER中union,cube,rollup,cumpute运算符使用说明

Jun 07, 2016 pm 05:59 PM
rollup union

union,cube,rollup,cumpute运算符的使用技巧。

/*
--1 UNION 运算符是将两个或更多查询的结果组合为单个结果集
使用 UNION 组合查询的结果集有两个最基本的规则:
1。所有查询中的列数和列的顺序必须相同。
2。数据类型必须兼容
a.UNION的结果集列名与第一个select语句中的结果集中的列名相同,其他select语句的结果集列名被忽略
b.默认情况下,UNION 运算符是从结果集中删除重复行。如果使用all关键字,那么结果集将包含所有行并且不删除重复行
c.sql是从左到右对包含UNION 运算符的语句进行取值,使用括号可以改变求值顺序
--例如:
*/
select * from tablea
union all
(
select * from tableb
union all
select * from tablec
)
/*
这样就可以先对tableb和tablec合并,再合并tablea
d.如果要将合并后的结果集保存到一个新数据表中,那么into语句必须加入到第一条select中
e.只可以在最后一条select语句中使用 order by 和 compute 子句,这样影响到最终合并结果的排序和计数汇总
f.group by 和 having 子句可以在单独一个select查询中使用,它们不影响最终结果
*/
--2 CUBE 汇总数据
/*
CUBE 运算符生成的结果集是多维数据集。多维数据集是事实数据的扩展,事实数据即记录个别事件的数据。
扩展建立在用户打算分析的列上。这些列被称为维。多维数据集是一个结果集,其中包含了各维度的所有可能组合的交叉表格。
CUBE 运算符在 SELECT 语句的 GROUP BY 子句中指定。该语句的选择列表应包含维度列和聚合函数表达式。
GROUP BY 应指定维度列和关键字 WITH CUBE。结果集将包含维度列中各值的所有可能组合,以及与这些维度值组合相匹配的基础行中的聚合值。
*/
--下列查询返回的结果集中,将包含 Item 和 Color 的所有可能组合的 Quantity 小计:
-->Title:生成測試數據
-->Author:wufeng4552
-->Date :2009-09-10 14:36:20
if not object_id('Tempdb..#t') is null
drop table #t
Go
Create table #t([Item] nvarchar(5),[Color] nvarchar(4),[Quantity] int)
Insert #t
select N'Table',N'Blue',124 union all
select N'Table',N'Red',223 union all
select N'Chair',N'Blue',101 union all
select N'Chair',N'Red',210
Go
select [Item],
[Color],
sum([Quantity])[Quantity]
from #t group by [Item],[Color] with cube
/*
Item Color Quantity
----- ----- -----------
Chair Blue 101
Chair Red 210
Chair NULL 311
Table Blue 124
Table Red 223
Table NULL 347
NULL NULL 658
NULL Blue 225
NULL Red 433
*/
/*CUBE 操作所生成的空值带来一个问题:如何区分 CUBE 操作所生成的 NULL 值和从实际数据中返回的 NULL 值?
这个问题可用 GROUPING 函数解决。
如果列中的值来自事实数据,则 GROUPING 函数返回 0;如果列中的值是 CUBE 操作所生成的 NULL,则返回 1。
在 CUBE 操作中,所生成的 NULL 代表全体值。可将 SELECT 语句写成使用 GROUPING 函数将所生成的 NULL 替换为字符串 ALL。
因为事实数据中的 NULL 表明数据值未知,所以 SELECT 语句还可译码为返回字符串 UNKNOWN 替代来自事实数据的 NULL。
例如:
*/
-->Title:生成測試數據
-->Author:wufeng4552
-->Date :2009-09-10 14:36:20
if not object_id('Tempdb..#t') is null
drop table #t
Go
Create table #t([Item] nvarchar(5),[Color] nvarchar(4),[Quantity] int)
Insert #t
select N'Table',N'Blue',124 union all
select N'Table',N'Red',223 union all
select N'Chair',N'Blue',101 union all
select N'Chair',N'Red',210
Go
select [Item]=case when grouping([Item])=1 then 'ALL' else isnull(Item, 'UNKNOWN')end,
[Color]=case when grouping([Color])=1 then 'ALL' else isnull([Color],'UNKNOWN')end,
sum([Quantity])[Quantity]
from #t group by [Item],[Color] with cube
/*
Item Color Quantity
----- ----- -----------
Chair Blue 101
Chair Red 210
Chair ALL 311
Table Blue 124
Table Red 223
Table ALL 347
ALL ALL 658
ALL Blue 225
ALL Red 433
(9 個資料列受到影響)
*/
/*
包含带有许多维度的 CUBE 的 SELECT 语句可能生成很大的结果集,因为这些语句会为所有维度中值的所有组合生成行。
这些大结果集包含的数据可能过多而不易于阅读和理解。这个问题有一种解决办法是将 SELECT 语句放在视图中:
*/
create view view_cube
as
select [Item]=case when grouping([Item])=1 then 'ALL' else isnull(Item, 'UNKNOWN')end,
[Color]=case when grouping([Color])=1 then 'ALL' else isnull([Color],'UNKNOWN')end,
sum([Quantity])[Quantity]
from tb group by [Item],[Color] with cube --視圖中不能用臨時表,故改之
--然后即可用该视图来只查询您感兴趣的维度值:
SELECT *
FROM InvCube
WHERE Item = 'Chair' AND Color = 'ALL'
/*
Item Color QtySum
-------------------- -------------------- ---------
Chair ALL 311.00
*/
--3 ROLLUP 汇总数据
/*
用 ROLLUP 汇总数据在生成包含小计和合计的报表时,ROLLUP 运算符很有用。
ROLLUP 运算符生成的结果集类似于 CUBE 运算符所生成的结果集。
CUBE 和 ROLLUP 之间的区别在于: CUBE 生成的结果集显示了所选列中值的所有组合的聚合。
ROLLUP 生成的结果集显示了所选列中值的某一层次结构的聚合。 例如,简单表 #t
中包含:Item Color Quantity
*/
select [Item]=case when grouping([Item])=1 then 'ALL' else isnull(Item, 'UNKNOWN')end,
[Color]=case when grouping([Color])=1 then 'ALL' else isnull([Color],'UNKNOWN')end,
sum([Quantity])[Quantity]
from #t group by [Item],[Color] with rollup
/*
Item Color Quantity
----- ----- -----------
Chair Blue 101
Chair Red 210
Chair ALL 311
Table Blue 124
Table Red 223
Table ALL 347
ALL ALL 658
(7 個資料列受到影響)
*/
/*
如果查询中的 ROLLUP 关键字更改为 CUBE,那么 CUBE 结果集与上述结果相同,只是在结果集的末尾还会返回下列两行:ALL Blue 225.00
ALL Red 433.00
CUBE 操作为 Item 和 Color 中值的可能组合生成行。
例如,CUBE 不仅报告与 Item 值 Chair 相组合的 Color 值的所有可能组合(Red、Blue 和 Red + Blue),
而且报告与 Color 值 Red 相组合的 Item 值的所有可能组合(Chair、Table 和 Chair + Table)。
对于 GROUP BY 子句中右边的列中的每个值,ROLLUP 操作并不报告左边一列(或左边各列)中值的所有可能组合。例如,
ROLLUP 并不对每个 Color 值报告 Item 值的所有可能组合。
ROLLUP 操作的结果集具有类似于 COMPUTE BY 所返回结果集的功能;然而,ROLLUP 具有下列优点: ROLLUP 返回单个结果集;COMPUTE BY 返回多个结果集,而多个结果集会增加应用程序代码的复杂性。
ROLLUP 可以在服务器游标中使用;COMPUTE BY 不可以。
有时,查询优化器为 ROLLUP 生成的执行计划比为 COMPUTE BY 生成的更为高效。
*/
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use union in c language How to use union in c language Sep 27, 2023 am 11:00 AM

The use of union in C language is a special data type that allows different data types to be stored in the same memory location. The use of union can help us save memory space and facilitate conversion between different data types. When using union, you need to note that the corresponding member is valid and only one member can be accessed at the same time.

How to use the FULL OUTER JOIN function in MySQL to obtain the union of two tables How to use the FULL OUTER JOIN function in MySQL to obtain the union of two tables Jul 26, 2023 pm 05:45 PM

How to use the FULLOUTERJOIN function in MySQL to obtain the union of two tables. In MySQL, the FULLOUTERJOIN function is a powerful join operation that combines inner joins and outer joins. It can be used to get the union of two tables, that is, combine all the data in the two tables into a single result set. This article will introduce the usage of the FULLOUTERJOIN function and provide some sample code to help readers better understand. FULLOUTERJOIN function

How to use mysql union to implement full outer join query How to use mysql union to implement full outer join query May 30, 2023 pm 06:49 PM

1. Union is not a method of multi-table connection query. It combines the query results of multiple query sentences into one result and removes duplicate data. 2. Full outer join queries the data of the left table and the right table, and then connects according to the connection conditions. Example #Use the left outer Aunion and the right outer BSELECT*FROMt_categorycLEFTOUTERJOINt_productpONc.cid=p.cnounionSELECT*FROMt_categorycRIGHTOUTERJOINt_productpONc.cid=p.cno

How does java define the Union class to realize the coexistence of data bodies? How does java define the Union class to realize the coexistence of data bodies? May 14, 2023 pm 03:34 PM

Define the Union class to implement the coexistence of data bodies. In the C/C++ language, a union, also known as a union, is a data structure similar to a struct. A union, like a struct, can contain many data types and variables. The difference between the two is as follows: all variables in a struct "coexist", and all variables are effective at the same time. Each variable occupies Different memory spaces; in a union, each variable is "mutually exclusive", only one variable is effective at the same time, and all variables occupy the same memory space. When multiple data need to share memory or only one of multiple data needs to be taken at a time, a union can be used. in Java

With a total of US$65 million in financing, can the new Rollup Eclipse open up the asset cycle of Solana and Ethereum? With a total of US$65 million in financing, can the new Rollup Eclipse open up the asset cycle of Solana and Ethereum? Mar 24, 2024 am 09:01 AM

On March 11, 2024, EclipseLabs announced the completion of a $50 million Series A financing, jointly led by Placeholder and HackVC. In 2022, Eclipse has completed US$15 million in Pre-seed and seed round financing at a valuation of over US$100 million. At present, the cumulative financing amount of this project has reached 65 million US dollars. It is said that Eclipse’s goal is to build a Rollup platform with core advantages and aims to enhance the compatibility, security and scalability of blockchain technology. The Eclipse project will be introduced in detail below. The core theme of Eclipse: Build a stronger La through the performance of Solana Virtual Machine (SVM)

How to use Union to optimize Like statement in MySQL How to use Union to optimize Like statement in MySQL May 31, 2023 pm 03:55 PM

Optimize the Like statement with Union 1) Sometimes, you may need to use the or operator for comparison in the query. When the or keyword is used too frequently in the where clause, it may cause the MySQL optimizer to mistakenly choose a full table scan to retrieve records. The union clause can make queries execute faster, especially when one of the queries has an optimized index and the other query also has an optimized index. For example, when there are indexes on first_name and last_name respectively, execute the following query statement: mysql>select*fromstudentswherefirst_namelike'A

How to optimize UNION through MySQL to improve performance How to optimize UNION through MySQL to improve performance May 11, 2023 pm 05:40 PM

In many database applications, we are faced with situations where we need to integrate data from multiple data sources. MySQL's UNION statement is a way to solve this situation, which allows us to merge the result sets of two or more SELECT statements into one. While this is a very convenient feature, UNION statements can also cause performance issues on your system if not optimized. This article will explore how to optimize UNION to improve performance through MySQL. Use UNIONALL while using U

Summer of Rollup: Overview of Established and Emerging Rollup Projects Summer of Rollup: Overview of Established and Emerging Rollup Projects Mar 03, 2024 pm 01:04 PM

Written by: Stanley, KernelVentures Compiled by: 0xxz, Golden Finance 1. Rollup Track Background 1.1 Track Introduction Rollup is one of the Layer2 solutions. By transferring the calculation and storage of transactions on the Ethereum main network (i.e. Layer1) to Layer2 for processing and compression, The compressed data is then uploaded to the Ethereum mainnet to expand Ethereum performance. The emergence of Rollup makes the gas fee of Layer 2 much lower than that of the main network, saving gas consumption, faster TPS, etc., making transactions and interactions smoother. Some mainstream Rollup chains that have been launched such as Arbitrum, Optimism, Base, and ZK Rollup such as

See all articles