Sql-Server-2005

統計 SQL 查詢

  • September 13, 2019

大家好,我只是想知道是否有人可以建議編寫此查詢的最簡單方法。以這種方式編寫子查詢 HomePageHits 的問題是為 Hits 和 HomePageHits 列帶來相同的記錄。Action 是 mytable 表上的一列。

SELECT 
,KEYID
,DATE
,COUNT(*) Hits
,(select COUNT(*) from mytable where Action = 'Home') as HomePageHits
from mytable where column = 'Home'
where date = getdate()-5 and keyid = 12345
DECLARE @d DATE = DATEADD(DAY, -5, CURRENT_TIMESTAMP);

SELECT 
 keyid = 12345,
 [date] = d,
 Hits = COUNT(*),
 HomePageHits = COUNT(CASE WHEN Action = 'Home' THEN 1 END)
FROM dbo.mytable
WHERE [date] >= @d
 AND [date] < DATEADD(DAY, 1, @d)
 AND keyid = 12345;

(我假設where column='Home'是一個錯字。)

一些技巧:

引用自:https://dba.stackexchange.com/questions/77644