0

我有一张如下表:

并且我想按DAY计算PageURL和GROUP列中说“ab”和“cd”的出现次数(即,无论一天出现多少次,它都算作1)。

ID  User  Activity  PageURL  ActDateTime
 1  Me    act1      abcd     2013-01-17 19:09:01.040
 2  Me    act2      cdab     2013-01-17 19:09:06.613
 3  You   act2      xyza     2013-01-30 16:10:50.177
 4  Me    act3      xyab     2013-01-30 10:35:09.037

我想要 2 列...1 用于“ab”计数,1 用于“cd”计数。

在上面的示例中,“ab”有 3 个计数,但我只会算作 2,因为前 2 个发生在同一天(所以算作 1)。

同样,PageURL 列中的“cd”有 2 个计数,但我只想算作 1,因为也发生在同一天。

此外,我想按月份分组,即 Jan-12、Feb-12、March-12、April-12 ...等。

非常感谢一些帮助和建议。谢谢!

这是我到目前为止所做的(但它没有考虑按 DAY 分组)

SELECT USER,
       department,
       activity,
       [MonthYear] = DATENAME(mm, ActDateTime)+ ' - ' + 
                                  DATENAME(yy, actdatetime), 
       [ab] = sum(case when pageURL like '%ab%' THEN 1 else 0 END), 
       [cd]= sum(CASE WHEN pageURL LIKE '%cd%'THEN 1 ELSE 0 END)
FROM activityLog
GROUP BY USER,
         department,
         activity,
         DATENAME(mm, ActDateTime)+ ' - ' + 
         DATENAME(yy, ActDateTime)
ORDER BY USER,
         department,
         activity,
         DATENAME(mm, ActDateTime)+ ' - ' + DATENAME(yy, ActDateTime)
4

3 回答 3

2

我认为这应该可以创建您的计数:

SELECT
  cast(ActDateTime as Date) as DateOnly, 
  SUM(CASE WHEN PageUrl Like '%ab%' THEN 1 ELSE 0 END) as ABCount,
  SUM(CASE WHEN PageUrl Like '%cd%' THEN 1 ELSE 0 END) as CDCount
FROM Table1 
GROUP BY cast(ActDateTime as Date)

SQL小提琴

于 2013-02-22T05:43:44.103 回答
1

第一个查询以按天计算:

SELECT cast(ActDateTime AS Date) AS DateOnly,
       CASE
           WHEN SUM(CASE WHEN PageUrl LIKE '%ab%' THEN 1 ELSE 0 END) >=1 THEN 1
           ELSE 0
       END AS ABCount,
       CASE
           WHEN SUM(CASE WHEN PageUrl LIKE '%cd%' THEN 1 ELSE 0 END) >=1 THEN 1
           ELSE 0
       END AS CDCount
FROM activityLog
GROUP BY cast(ActDateTime AS Date)

第二个查询以获得所需的输出:

SQLFIDDLE示例

SELECT DATENAME(month, a.ActDateTime)+ ' - ' + DATENAME(yy, a.ActDateTime)
      ,SUM(a.ABCount) as ABCount
      ,SUM(a.CDCount) as CDCount
FROM (SELECT cast(ActDateTime AS Date) AS ActDateTime,
       CASE
           WHEN SUM(CASE WHEN PageUrl LIKE '%ab%' THEN 1 ELSE 0 END) >=1 THEN 1
           ELSE 0
       END AS ABCount,
       CASE
           WHEN SUM(CASE WHEN PageUrl LIKE '%cd%' THEN 1 ELSE 0 END) >=1 THEN 1
           ELSE 0
       END AS CDCount
FROM activityLog
GROUP BY cast(ActDateTime AS Date))a
GROUP BY DATENAME(month, a.ActDateTime)+ ' - ' + DATENAME(yy, a.actdatetime)
ORDER BY DATENAME(month, a.ActDateTime)+ ' - ' + DATENAME(yy, a.actdatetime)

结果:

|       COLUMN_0 | ABCOUNT | CDCOUNT |
--------------------------------------
| January - 2013 |       2 |       1 |
于 2013-03-04T21:55:25.943 回答
0
SELECT Thing
      ,COUNT(*) NumDays
FROM  (SELECT LEFT(PageURL, 2) AS Thing
       ,DateTime
       FROM table
       ALL
       SELECT RIGHT(PageURL, 2)
             ,DateTime
       FROM table) UniqueDays

由于您在问题中使用的关键词,这将无法正常工作。

一般来说,使用实际的列/表名称更容易,因此答案可以反映这些 - 它避免了混淆。

于 2013-02-22T05:17:14.340 回答