根据特定条件的行数

时间:2018-10-16 11:17:04

标签: sql sql-server

我有一个按sessionidtimestamp ts排序的表。

我要查找的是sessionids的计数,该计数在同一会话screen_name = 'listpage'中的购物车页面视图screen_name = 'checkout_cart'之后具有至少一个列表页面视图sessionid

表格:

sessionid screen_name ts

11 checkout_cart 1593
11 checkout_cart 1594
12 checkout_cart 1890
12 home_page 1892
12 list_page 1894
12 checkout_cart 1896
13 list_page 1900
13 checkout_cart 1902
13 home_page 1904
14 checkout_cart 1990
14 home_page 1992
14 list_page 1994
14 checkout_cart 1996

基于该表,我的计数应为2 session id 12 and 14,13,因为list_Pagecart_page之前 请帮我写一个查询,我坚持逻辑。

3 个答案:

答案 0 :(得分:2)

尝试使用该版本:

select t.sessionid,count(*)
from your_table t
where screen_name='listpage'
and exists
(
    select 1
    from your_table t2
    where t2.screen_name='checkout_cart'
    and t2.ts<t.ts and t.sessionid=t2.sessionid
)
group by t.sessionid

编辑:添加了sessionid加入条件,一开始错过了

答案 1 :(得分:1)

一种方法使用聚合。要获取会话列表:

function onChange(e) {     
if (e.range.getA1Notation() == 'C8') {  
  if (/^\w+$/.test(e.value)) {          
  eval(e.value)();
   }
  }
 }

function HideAll() {
 var ss = SpreadsheetApp.getActiveSpreadsheet();
 var sheet = ss.getActiveSheet();
  sheet.hideRows(9,189);  // Hide All SW01 Options 
 }

function SG30052MP() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
   sheet.hideRows(9,189);  // Hide all SW01 to reset
   sheet.showRows(11,15);  // Show SW01 SG300-52MP
    }

function SG30052P() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
   sheet.hideRows(9,189);  // Hide all SW01 to reset
   sheet.showRows(26,15);  // Show SW01 SG300-52P
    }`

要获取计数,请使用子查询或CTE:

select sessionid
from t
where screen_name in ('listpage', 'checkout_cart')  -- only needed for performance
group by sessionid
having max(case when screen_name = 'listpage' then ts end) > min(case when screen_name = 'checkout_cart' then ts end)

答案 2 :(得分:0)

select sessionid, Count_Test = count(case when screen_name in ('listpage','checkout_cart') then 1 else 0 end )
from table_name
group by sessionid 

...使用此方法,您也不需要执行子查询。它是带有case语句的简单汇总。