我在SQL Server中有一个包含这些记录的表:
ID Date Time -- --------- ---- 1 09/05/02 6:00 2 09/05/02 8:00 3 09/05/03 6:00 4 09/05/04 8:00 5 09/05/04 6:00
我想选择那些在一天中有重复两次或两次的记录的身份证明。
我如何在SQL Server中执行此操作?
答案 0 :(得分:2)
类似的东西:
select table_1.id, table_1.date from
table as table_1 inner join table as table_2 on
table_1.date = table_2.date
and
table_1.id <> table_2.id
应该可以正常工作。
答案 1 :(得分:1)
这将返回预期结果
declare @aa table (id int,datee date)
insert into @aa
select 1, '09/05/02' union all
select 2, '09/05/02' union all
select 3, '09/05/03' union all
select 4, '09/05/04' union all
select 5, '09/05/04'
select * from @aa where datee in (
select datee from @aa group by datee having COUNT(datee)>1)
答案 2 :(得分:1)
此查询只选择ID = 1的记录和重复两次或多次2的日期:
SELECT * FROM MyTable WHERE (Date IN (SELECT Date FROM MyTable WHERE (ID = 1) GROUP BY Date HAVING (COUNT(Date) % 2 = 0) ) ) AND (ID = 1)
答案 3 :(得分:0)
CREATE TABLE MyTable(ID INTEGER, Date DATETIME)
INSERT INTO MyTable VALUES (1, '09/05/02 6:00')
INSERT INTO MyTable VALUES (1, '09/05/02 8:00')
INSERT INTO MyTable VALUES (2, '09/05/03 6:00')
INSERT INTO MyTable VALUES (3, '09/05/04 8:00')
INSERT INTO MyTable VALUES (4, '09/05/04 6:00')
SELECT t1.*
FROM MyTable t1
INNER JOIN (
SELECT t1.ID, Date1 = t1.Date, Date2 = t2.Date
FROM MyTable t1
INNER JOIN MyTable t2 ON CAST(t2.Date AS INTEGER) = CAST(t1.Date AS INTEGER)
AND DATEPART(HOUR, t2.Date) = DATEPART(HOUR, t1.Date) - 2
AND t2.ID = t1.ID
) t2 ON t2.ID = t1.ID AND t1.Date IN (t2.Date1, t2.Date2)
答案 4 :(得分:0)
我的布局对于我来说不是很清楚日期和时间是在单独的列中,还是只有一列。那就是,你有
ID theDate theTime
-- -------- -------
1 09/05/02 6:00
1 09/05/02 8:00
2 09/05/03 6:00
3 09/05/04 8:00
4 09/05/04 6:00
或
ID theDateTime
-- -------------
1 09/05/02 6:00
1 09/05/02 8:00
2 09/05/03 6:00
3 09/05/04 8:00
4 09/05/04 6:00
如果第一个是真的,那么Ramesh几乎(但不完全是)正确的答案:
select *
from theTable
where theDate in (
select theDate
from theTable
group by theDate
having count(theDate) % 2 = 0
)
如果第二个是真的,那么你的工作要复杂得多 - 我会考虑一下。