SQL concat很少选择成一个大表

时间:2016-10-19 08:52:46

标签: sql sql-server datetime

我有数据表:

  1. YYYY / MM / DD HH:MM:SS - 观看次数,点击次数等。
  2. YYYY / MM / DD HH:MM:SS - ......
  3. 我希望将所有这些列加总为和值。 喜欢: 1. YYYY / MM / DD - 观看总和,点击总和

    我做了什么: 1.查询foreach列。 对于观点;

    select 
      cast([EventTime] as date) as 'Date',
      Count([Id]) as 'Views'
    from [TelemetryData] 
    where [DiscountId] = '8773fd1b-f0c0-41fd-b0a0-ab8238f227f5'
      and [EventName]     = 'DiscountView'
    group by cast([EventTime] as date)
    order by cast([EventTime] as date) asc
    

    每日点击次数:

    select 
      cast([EventTime] as date) as 'Date',
      Count([Id]) as 'Clicks'
    from [TelemetryData] 
    where [DiscountId] = '8773fd1b-f0c0-41fd-b0a0-ab8238f227f5'
      and [EventName] =     'DiscountClick'
    group by cast([EventTime] as date)
    order by cast([EventTime] as date) asc
    

    我怎样才能将它们全部排成一行?

2 个答案:

答案 0 :(得分:1)

尝试检查和总结:

SELECT cast([EventTime] as date) as 'Date', SUM(case when [EventName]='DiscountClick' then 1 else 0 end) as 'Clicks', SUM(case when [EventName]='DiscountView' then 1 else 0 end) as 'Views'
from [TelemetryData] 
where [DiscountId] = '8773fd1b-f0c0-41fd-b0a0-ab8238f227f5'
and ([EventName] = 'DiscountView' or [EventName] = 'DiscountClick')
group by cast([EventTime] as date)
order by cast([EventTime] as date) asc

改变了什么:

我们首先选择了哪个列来过滤视图和点击。

然后我们使用SUM但是在EVENT = SOMETHING时使用CASE我们加1,否则为0。

通过您的论坛,您可以在一次查询中获得两天。

答案 1 :(得分:0)

使用SUM和CASE ..

sum(case when [DiscountId] = '8773fd1b-f0c0-41fd-b0a0-ab8238f227f5'
  and [EventName] =     'DiscountClick' then noofclicks column else 0 end
) as clicks

sum(case when [DiscountId] = '8773fd1b-f0c0-41fd-b0a0-ab8238f227f5'
  and [EventName] =     'DiscountView' then view column else 0 end
) as views

以及其他......

from
table
group by cast([EventTime] as date)
order by cast([EventTime] as date)