去重的多种方法
思韵闪耀
2012-11-17
0
Create table #sales_details
(
	sales_id int identity(1,1),
	item_id int not null,
	qty int not null,
	unit_price decimal(12,2) not null,
	sales_date datetime not null
)

insert into #sales_details (item_id,qty,unit_price,sales_date)
select 1001,5,200,'2012-09-03 11:16:28' union all
select 1001,2,200,'2012-09-04 19:22:11' union all
select 1002,15,1300,'2012-09-06 14:26:40' union all
select 1003,8,78,'2012-09-19 15:11:19' union all
select 1001,6,200,'2012-09-22 16:36:11' union all
select 1004,22,1000,'2012-09-23 16:51:34' union all
select 1004,11,1000,'2012-09-23 17:29:38' union all
select 1002,29,1300,'2012-09-23 18:20:10' union all
select 1002,6,1300,'2012-09-26 19:40:41' union all
select 1002,33,1300,'2012-09-30 20:26:29' 

Assume that you want to find out distinct item_id from the above table. You can use many methods. Some of them are listed below

--Method 1 : Use DISTINCT keyword

select distinct item_id from #sales_details 

--Method 2 : Use GROUP BY Clause
select item_id from #sales_details
Group by item_id

--Method 3 : UNION the same table
select item_id from #sales_details
UNION
select item_id from #sales_details 

--Method 4 : UNION the same table with not selecting any rows from secondly sepecified table
select item_id from #sales_details
UNION    --union会做一个distinct
select item_id from #sales_details where 1=0

--Method 5 : UNION the table with Empty result

select distinct item_id from #sales_details 

select item_id from #sales_details
UNION
select 0 where 1=0

--Method 6 : Use Row_number() function
select item_id from
(
	select row_number() over (partition by item_id order by item_id) as sno,* from #sales_details
) as t
where sno=1

参考:distinct


【版权声明】
本站部分内容来源于互联网,本站不拥有所有权,不承担相关法律责任。如果发现本站有侵权的内容,欢迎发送邮件至masing@13sy.com 举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。

WAN

相关内容

续订Exchange Se...
每个证书都有内置的到期日期。 在Exchange Server中,...
2022-09-16
SkidMap病毒利用Re...
摘要 利用redis未授权访问漏洞入侵云主机; 下载门罗币、莱特币...
2022-04-09
如果在crontab -e...
今天登录服务器,发现之前所有的计划任务都不见了 然后尝试添加 [r...
2022-04-09
了解SQL Server中...
Terabytes of data, millions ofrow...
2022-02-24
sql数据库分离附加_使用...
sql数据库分离附加_使用分离和附加方法移动SQL数据库 sql数...
2022-01-11
免费下载 Windows ...
免费下载 Windows 8.1 Update 1 (KB2919...
2022-01-09

热门资讯

sql中int型与varcha... sql中int转varchar或nvarchar,varchar或nvarchar转int的方法: ...
SQLSERVERAGENT ... 上的 SQLSERVERAGENT 服务启动过,然后又停止了。 (ObjectExplorer) 可...
SQL Server 中4个系... SQL Server 中4个系统数据库,Master、Model、Msdb、Tempdb 系统数据库...
SQL Server中如何设置... 对于已经建好的数据库表,是不能在SQL Server Management中可视化地修改ID为自增长...
该表已为了复制而被发布,所以... 场景:从发布库上将一数据库移到另一服务器,在对表改名时提示该表已为了复制而被发布,所以无法重命名。 ...
SQL Server 2008... SQL Server 2008 R2运行越久,占用内存会越来越大。 第一种: 有了上边的分析结果,解...
SQL Server (MSS... SQL Server (MSSQLSERVER) 启动后 自动生成文件 audittrace2022...
如果使用没有提供选项值的 Sq... 如果使用没有提供选项值的 SqlDependency,必须先调用 SqlDependency.Sta...
传递给数据库 'master'... 传递给数据库 master 中的日志扫描操作的日志扫描号无效 错误:连接数据库的时候提示:SQL S...
数据仓库SSAS+SSIS+... 数据仓库SSAS+SSIS+SSRS SSAS- 1,用ssas生成多维度,然后利用excel的da...