SQL:选择该日期的唯一日期,总计和该日期的总计以及另一个参数

时间:2014-04-02 00:03:25

标签: mysql sql sql-server

在SQL中,我试图获得3个类别的返回。

  1. 独特日期
  2. 当天访问的人数。
  3. 1日访问次数和特定日期访问次数
  4. 我有我的SQL

    SELECT
    DISTINCT DATEADD(dd, 0, DATEDIFF(dd, 0, visit_date)) as theday, 
    (SELECT count(DISTINCT visit_id)) as uniques, 
    (SELECT count(DISTINCT visit_id) 
    FROM visitors 
    WHERE visit_id IN (
    SELECT DISTINCT visit_id 
    FROM visitors 
    WHERE (visit_date >= '2014-03-29 00:00:00.000' 
    AND visit_date <= '2014-03-30 00:00:00.000')
    )
    ) as visited_again
    FROM visitors
    WHERE visit_date >= '2014-01-01 00:00:00.000'
    GROUP BY DATEADD(dd, 0, DATEDIFF(dd, 0, visit_date))
    ORDER BY theday DESC;
    

    它非常适合给我#1和#2,但第三个只给我一个唯一的数字,每个日期重复一次。

    上面的SQL返回如下所示的结果:

       theday    |    uniques    |    visited_again
    -------------+---------------+------------------
    2014-03-30   |    900000     |    84450
    2014-03-29   |    789433     |    84450
    2014-03-28   |    823010     |    84450
    2014-03-27   |    901101     |    84450
    2014-03-26   |    773556     |    84450
    2014-03-25   |    345789     |    84450
    

1 个答案:

答案 0 :(得分:1)

在您尝试计算重复访问次数的位置,外部查询中的各个visit_id值不再可用,因此您无法单独查看每个visit_id值。试试这个:

DECLARE @d DATETIME;
SET @d = '2014-03-30 00:00:00.000';

WITH V(visit_id,theday,special_date_flag) AS (
  SELECT DISTINCT
    visit_id,
    visit_date,
    CASE WHEN visit_id IN (
      SELECT visit_id FROM visitors
      WHERE visit_date >= @d AND visit_date < @d+1
      --note change to select 1, not 2 dates here!
    ) THEN 1 ELSE NULL END
  FROM visitors
)
SELECT
  theday, 
  count(visit_id) as uniques,
  count(special_date_flag) as visited_again
FROM V
WHERE thedate >= '2014-01-01 00:00:00.000' 
GROUP BY theday
ORDER BY theday DESC

此查询首先创建一个(visit_id,theday)值的虚拟表,每个行都有第三列,以指示特定的visit_id是特殊日期的其中一个。

还有其他方法可以做到这一点 - 你真的只需要每个visit_id的标志,而不是(visit_id,theday)对,但这更容易编写。