日期:2014-05-17 浏览次数:20551 次
----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-10-17 15:34:50
-- Version:
-- Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64)
-- Dec 28 2012 20:23:12
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: ) (Hypervisor)
--
----------------------------------------------------------------
--> 测试数据:[huang]
if object_id('[huang]') is not null drop table [huang]
go
create table [huang]([ID] int,[Name] varchar(4),[UserID] int)
insert [huang]
select 1,'水果',999 union all
select 1,'蔬菜',999 union all
select 1,'零食',333 union all
select 1,'饮料',999 union ALL
select 1,'干货',555 union all
select 1,'海鲜',999 union all
select 1,'肉食',777
--------------开始查询--------------------------
DECLARE @n INT
SET @n=1
SELECT *
FROM huang
WHERE userid IN (
SELECT userid
FROM (
select userid,ROW_NUMBER()OVER(PARTITION BY userid ORDER BY id)oid
from [huang])a
GROUP BY userid
HAVING MAX(oid)=@n
)
----------------结果----------------------------
/*
*/
create table js
(ID int, Name varchar(10), UserID varchar(10))
insert into js
select 1,'水果','999' union all
select 1,'蔬菜','999' union all
select 1,'零食','333' union all
select 1,'饮料','999' union all
select 1,'干货','555' union all
select 1,'海鲜','999' union all
select 1,'肉食','777'
-- UserID出现1次的数据
select a.ID,a.name,a.UserID
from js a
inner join
(select UserID from js
group by UserID having