为此示例编写查询

时间:2016-09-23 05:25:40

标签: sql sql-server tsql

我有一个包含以下数据的表格,我想写一个查询给我ID和连接的天数。

例如id 1给我2次(2016-09-20,2016-09-22)

enter image description here

5 个答案:

答案 0 :(得分:1)

SELECT id, COUNT(DISTINCT convert(date, startTime)) as noOfDays
FROM your_table
GROUP BY id

答案 1 :(得分:0)

如果您仅查看基于startdate列的日期,请使用以下查询。

SELECT COUNT(DISTINCT cast (StartTime as date)) DaysCount
FROM YourTable
Where ID=1

答案 2 :(得分:0)

你可以这样做

Select id,TotalCount=Count(id) from YourTable group by id

答案 3 :(得分:0)

虽然问题不是很明确,但我认为您正在尝试获取每个ID的连接天数总数,并考虑到每天多个连接(所有连接都被视为一个连接)。连接可能会持续数天(取决于EndTime),在这种情况下,这些天数也应计算在内。

试试这个:

declare @tt table(id int, StartTime datetime, EndTime datetime)
insert into @tt values
 (1, '2016-09-20 13:01', '2016-09-20 13:30')
,(1, '2016-09-20 14:20', '2016-09-20 16:09')
,(1, '2016-09-20 17:20', '2016-09-20 17:51')
,(1, '2016-09-22 23:20', '2016-09-22 23:40')

,(2, '2016-09-20 14:20', '2016-09-20 16:09')
,(2, '2016-09-20 16:01', '2016-09-20 16:09')

,(3, '2016-09-20 14:20', '2016-09-20 14:56')
,(3, '2016-09-23 19:20', '2016-09-23 20:09')

,(4, '2016-09-20 22:20', '2016-09-20 23:00')

select * from @tt

;with cte1 as
(
    select ID, convert(Date, StartTime) as StartDate
    , convert(Date, max(EndTime)) as EndDate
    from @tt 
    group by id, convert(Date, StartTime)
), 
cte2 as 
(
    select *, DATEDIFF(day, StartDate, EndDate) +1 as DaysCount 
    from cte1
)
select id, sum(DaysCount) as DaysCount 
from cte2
group by id

答案 4 :(得分:0)

select id,count(distinct(dbo.GetDateInt(StartTime))) NoofDays from table_name group by id

注意:在sql server 2012中执行此查询,getDateInt()是数据库功能。返回日期仅限2016-09-23。