我试图获取不同的区号,这样我就可以在每次运行时根据周日期范围过滤报表中的前5位。
SELECT
[Area] AS 'AreaCode',
(SELECT COUNT(*) FROM gail_hazzards gh1 WHERE [gh1].[Area] = [gh].[Area]) AS 'AreaCount',
CONVERT(DATE, gh.[Timetag1], 201) AS 'Time'
FROM
gail_hazzards gh
GROUP BY gh.[Area], CONVERT(DATE, gh.[Timetag1], 201)
ORDER BY AreaCount DESC
结果:我一直在尝试添加子查询以获取不同的区号,但我在尝试正确使用时遇到问题:/
AreaCode AreaCount Time
480 683 2016-03-23
480 683 2016-03-24
480 683 2016-03-25
480 683 2016-03-29
480 683 2016-03-30
870 210 2016-04-15
870 210 2016-04-16
870 210 2016-04-19
870 210 2016-04-20
870 210 2016-04-21
答案 0 :(得分:0)
根据您问题中的描述,我希望查询看起来像这样:
SELECT [Area] AS AreaCode, COUNT(*) AS AreaCount,
CONVERT(DATE, gh.[Timetag1], 201) AS 'Time'
FROM gail_hazzards gh
WHERE gh.Timetag1 BETWEEN ? AND ?
GROUP BY gh.[Area]
ORDER BY AreaCount DESC;
我不确定"周时间范围"应该是,但它可能是这样的:
WHERE gh.Timetag1 BETWEEN DATEADD(DAY, -6, CAST(GETDATE() as DATE)) AND CAST(GETDATE() as DATE)
答案 1 :(得分:0)
试试这个,
select AreaCode,AreaCount,Time from (SELECT row_number() over(partition by Area order by [Timetag1] desc) as RowNum,
Area as AreaCode, COUNT(*) AS AreaCount,
CONVERT(varchar, Timetag1, 103) AS 'Time'
FROM gail_hazzards
GROUP BY Area,Timetag1) as tbl
where RowNum<6
order by AreaCode,Time
答案 2 :(得分:0)
SELECT DISTINCT(Area),
(SELECT COUNT(*) FROM [dbo].[tkg_gail_hazards] c WHERE c.Area = x.Area and CONVERT(date, c.TimeTag1, 102) >= CONVERT(date, @p_start, 102) AND CONVERT(date, c.TimeTag1, 102) <= CONVERT(date, @p_end, 102)) as 'Total'
FROM [dbo].[tkg_gail_hazards] x
ORDER BY Total desc;
上面的代码以及应用的一些过滤器为我提供了所需的数据 - 感谢大家的输入。