RGN - >区域名称,NPR - >需要针对每个区域计算的事件,RGF - >区域过滤器。所以在NPR我有汽车板块的事件,我需要为每个地区计算它们,并将其分成一周的7天。我的解决方案如下:
SELECT DISTINCT a.NAME,
COUNT(CASE WHEN DATEPART(dw,b.TM) = 1 THEN 1 ELSE null END) as MON,
COUNT(CASE WHEN DATEPART(dw,b.TM) = 2 THEN 1 ELSE null END) as TUE,
COUNT(CASE WHEN DATEPART(dw,b.TM) = 3 THEN 1 ELSE null END) as WED,
COUNT(CASE WHEN DATEPART(dw,b.TM) = 4 THEN 1 ELSE null END) as THU,
COUNT(CASE WHEN DATEPART(dw,b.TM) = 5 THEN 1 ELSE null END) as FRI,
COUNT(CASE WHEN DATEPART(dw,b.TM) = 6 THEN 1 ELSE null END) as SAT,
COUNT(CASE WHEN DATEPART(dw,b.TM) = 7 THEN 1 ELSE null END) as SUN
FROM RGN a
LEFT JOIN NPR b
ON a.ID IN (
SELECT c.RGID
FROM RGF c
WHERE RTRIM(b.NUM) like RTRIM((REPLACE(c.RGFLT,'?','_')))
)
Group by a.NAME;
在过滤器中,我需要将?
替换为_
以获得like()
表达式。
这个查询给了我很好的结果,但是在数据库中有4密耳的记录,就像20分钟就可以得到它。您是否知道如何做到完全相同但效率更高?
P.S。我尝试使用SUM()而不是计数,但它不会改变任何东西。
@Edit我的下一次尝试是SELECT FROM NPR
和join RGN
,它有点快但不够。
答案 0 :(得分:0)
SELECT a.NAME,
COUNT(CASE WHEN DATEPART(dw,b.TM) = 1 THEN 1 ELSE null END) as MON,
COUNT(CASE WHEN DATEPART(dw,b.TM) = 2 THEN 1 ELSE null END) as TUE,
COUNT(CASE WHEN DATEPART(dw,b.TM) = 3 THEN 1 ELSE null END) as WED,
COUNT(CASE WHEN DATEPART(dw,b.TM) = 4 THEN 1 ELSE null END) as THU,
COUNT(CASE WHEN DATEPART(dw,b.TM) = 5 THEN 1 ELSE null END) as FRI,
COUNT(CASE WHEN DATEPART(dw,b.TM) = 6 THEN 1 ELSE null END) as SAT,
COUNT(CASE WHEN DATEPART(dw,b.TM) = 7 THEN 1 ELSE null END) as SUN
FROM RGN a, RGF c
left JOIN NPR b
ON RTRIM(b.NUM) like RTRIM((REPLACE(c.RGFLT,'?','_')))
WHERE a.ID = c.RGID AND b.TM BETWEEN
Group by a.RGNAME
执行时间为100k行~4s,足够好,因为它是~12s