SQL查询 - 按名称和按星期几的查看访问

时间:2016-04-18 11:19:39

标签: sql-server

我在SQL方面相对缺乏经验,我有一个查询,我想在SQL-Server中运行。

所以我有两张桌子:

站点:

Id (PK) | SiteName

和访问:

Id (PK) | Duration | EntryTime | site_Id (FK > Sites)

我想创建一个表作为此查询的输出,如下所示:

SiteName | MondayVisitCount | TuesdayVisitCount | etc... 

我希望使用Visits表中的EntryTime字段以及与访问相关联的站点名称,在一周中的每一天进行总计访问次数计数。最终查询应实现日期范围,因此它是该日期范围内每周的每一天的累计访问次数。这是创建这个新表的过程我不明白,欢迎任何提示。

3 个答案:

答案 0 :(得分:0)

@jonny

我没有适当的数据可供测试,但您可以通过稍微改变我的查询来实现您的目标。

SELECT S.SITENAME AS SITENAME,
CASE WHEN DATENAME(DW, V.EntryTime) = 'Monday' THEN 0 ELSE 1 END AS 'MondayVisitCount ',
CASE WHEN DATENAME(DW, V.EntryTime ) = 'Tuesday' THEN 0 ELSE 1 END AS 'TuesdayVisitCount ',
FROM SITES AS S 
INNER JOIN VISITS AS V ON S.SITE_ID = V.SITE_ID

答案 1 :(得分:0)

DECLARE @T TABLE
(
    SiteID  INT,
    SiteName VARCHAR(100),
    MondayVisitCount Int,
    TuesdayVisitCount Int,
    WednesdayVisitCount Int,
    ThursdayVisitCount Int,
    FridayVisitCount Int,
    SaturdayVisitCount INT,
    SundayVisitCount Int
)


INSERT INTO @T

        ( 
          SiteID,
          SiteName ,
          MondayVisitCount ,
          TuesdayVisitCount ,
          WednesdayVisitCount ,
          ThursdayVisitCount ,
          FridayVisitCount ,
          SaturdayVisitCount ,
          SundayVisitCount
        )
SELECT ID, SiteName
FROM Sites


SELECT COUNT(*) AS N, Site_Id, DATEPART(weekday, EntryTime) AS [DayOfWeek]
INTO #tmpVisits
FROM [dbo].Visits WITH (NOLOCK)
--DATE FILTER GOES HERE
GROUP BY DATEPART(weekday, EntryTime), Site_Id

UPDATE @T
SET SundayVisitCount = tVisits.N
FROM @T AS tResult
INNER JOIN #tmpVisits AS tVisits ON tVisits.Site_Id = tResult.Id AND tVisits.[DayOfWeek] = 1

UPDATE @T
SET MondayVisitCount = tVisits.N
FROM @T AS tResult
INNER JOIN #tmpVisits AS tVisits ON tVisits.Site_Id = tResult.Id AND tVisits.[DayOfWeek] = 2
--.
--.
--.
--.
UPDATE @T
SET SaturdayVisitCount = tVisits.N
FROM @T AS tResult
INNER JOIN #tmpVisits AS tVisits ON tVisits.Site_Id = tResult.Id AND tVisits.[DayOfWeek] = 7


SELECT *
FROM @T

DROP TABLE #tmpVisits

答案 2 :(得分:0)

declare @startdate datetime = cast('2008/01/01' as datetime)
declare @enddate   datetime = cast('2008/07/31' as datetime)

select p.* 
        into sitevisits         --create a permanent table in database
from
(
select 1 as rectype,s.sitename , datename(DW,v.entrytime) as [Dayofweek],
        1 as [dayofweekcount]   --give pivot something to sum
from @site s
join  @visits v on v.siteid = s.id
where   v.entrytime between @startdate and @enddate

) s
pivot (sum(s.dayofweekcount) for s.[dayofweek] in ([Monday],[Tuesday],[Wednesday],[Thursday],[Friday],[Saturday],[Sunday]))  p
union
select p.* from
(
select 2 as rectype,'Grand Total' sitename, datename(DW,v.entrytime) as [Dayofweek],
        1 as [dayofweekcount]
from  @visits v 
where   v.entrytime between @startdate and @enddate
) s
pivot (sum(s.dayofweekcount) for s.[dayofweek] in ([Monday],[Tuesday],[Wednesday],[Thursday],[Friday],[Saturday],[Sunday]))  p