从2个表中按天分组

时间:2009-10-06 21:48:52

标签: sql sql-server sql-server-2005 tsql

我有2个表:“订单”和“访问”。在订单表中我保存了一些订单的详细信息,包括“userIP”和“orderDate”。在访问表中我每次访问我的网页时都会保存详细信息,包括“userIP”和“visitDate”。我正在使用ASP.NET和SQL SERVER 2005。 我想创建一个统计表,我保存了访问过的用户数量和订购的用户数量 BOTH GROUPED BY DAY 到目前为止我得到了:

  select count(userIP) as NumOfOrders,
         dateadd(dd, datediff(dd, 0, orderDate),0) as Date
    from Orders
group by dateadd(dd, datediff(dd, 0, orderDate), 0)

这很好用,给我按天分组的订单数量, 但是如何将按日分组的总访问次数添加到此?

2 个答案:

答案 0 :(得分:0)

SELECT COALESCE(O1.Date, V1.Date) Date,
       COALESCE(O1.NumOfOrders, 0) NumOfOrders,
       COALESCE(V1.TotalVisits, 0) TotalVisits
FROM 
     (select dateadd(dd,0, datediff(dd, 0, O.orderDate)) Date,
             count(O.userIP) NumOfOrders
        from Orders O
    group by dateadd(dd,0, datediff(dd, 0, O.orderDate))) O1
FULL JOIN
     (select dateadd(dd,0, datediff(dd, 0, V.visitDate)) Date,
             count(V.userIP) TotalVisits
        from Visits V
    group by dateadd(dd,0, datediff(dd, 0, V.visitDate))) V1
on O1.Date = V1.Date

答案 1 :(得分:0)

我会这样做:

SELECT v.userIP, NumOfVisits, NumOfOrders, v.Date
FROM (
    SELECT userIP, count(*) as NumOfVisits,
         dateadd(dd, datediff(dd, 0, visitDate),0) as Date
    FROM visits
    GROUP BY userIP, dateadd(dd, datediff(dd, 0, orderDate), 0)) v
LEFT JOIN (
    SELECT userIp, count(*) as NumOfOrders,
         dateadd(dd, datediff(dd, 0, orderDate),0) as Date
    FROM orders
    GROUP BY UserIP, dateadd(dd, datediff(dd, 0, orderDate), 0)) o
 ON o.UserIP = v.UserIP
    AND o.Date = v.Date

,你的结果应该是:

78.34.5.11 | 3 | 1 | 2009.10.06
78.34.5.19 | 9 | 0 | 2009.10.06

如果您不需要按userIP分组,则可以执行以下操作:

SELECT NumOfVisits, NumOfOrders, v.Date
FROM (
    SELECT count(*) as NumOfVisits,
         dateadd(dd, datediff(dd, 0, visitDate),0) as Date
    FROM visits
    GROUP BY dateadd(dd, datediff(dd, 0, visitDate), 0)) v
LEFT JOIN (
    SELECT count(*) as NumOfOrders,
         dateadd(dd, datediff(dd, 0, orderDate),0) as Date
    FROM orders
    GROUP BY dateadd(dd, datediff(dd, 0, orderDate), 0)) o
 ON o.Date = v.Date

,您的结果将如下所示:

12 | 1 | 2009.10.06