4

在弄清楚这其中的逻辑时遇到了一些麻烦。请参阅下面的两个查询:

查询一:

SELECT cId, crId, COUNT(EventType)
FROM Data
WHERE EventType='0' OR EventType='0p' OR EventType='n' OR EventType = 'np'
GROUP BY crId;

查询 2:

SELECT cId, crId, COUNT(EventType) AS Clicks
FROM Data
WHERE EventType='c'
GROUP BY crId;

只是想知道是否有一种方法可以使我在查询 2 结束时获得的列出现在查询 1 中。由于 where 语句不同,因此不确定该去哪里,以及我刚刚编写的任何子查询没有奏效。

提前致谢

4

4 回答 4

5
SELECT cId, crId, 
SUM(CASE WHEN EventType='0' OR EventType='0p' OR EventType='n' OR EventType = 'np' THEN 1 ELSE 0 END) AS Count_1,
SUM(CASE WHEN EventType='c' THEN 1 ELSE 0 END) AS Count_2
FROM Data
WHERE EventType IN ('0','0p','n','np','c')
GROUP BY crId;
于 2013-01-11T14:29:07.347 回答
2

您可以将两者结合起来,将第二个用作相关子查询。

SELECT 
  Data.cId, 
  Data.crId, 
  COUNT(EventType) AS event_type_count,
  click_counts.Clicks
FROM 
  Data
  /* Correlated subquery retrieves the Clicks (EventType 'c') per cId */
  LEFT JOIN  (
    SELECT cId, crId, COUNT(EventType) AS Clicks
    FROM Data
    WHERE EventType='c'
    GROUP BY crId
  ) AS click_count ON Data.cId = click_count.cId AND Data.crId = click_count.crId
/* OR chain replaced with IN() clause */
WHERE Data.EventType IN ('0','0p','n','np')
/* This GROUP BY should probably also include Data.cId... */
GROUP BY Data.crId;
于 2013-01-11T14:26:37.097 回答
2

您可以从表中查询一次并使用CASE语句来完成所有这些操作。

SELECT  cId, crId, 
        SUM(CASE WHEN EventType IN ('0', '0p', 'n', 'np') THEN 1 ELSE 0 END) as events,
        SUM(CASE WHEN EventType = 'c' THEN 1 ELSE 0 END) as clicks
FROM    Data
WHERE   EventType IN ('0', '0p', 'n', 'np', 'c')
GROUP BY crId;
于 2013-01-11T14:31:28.170 回答
0

你想用IN吗?

SELECT cId, crId, COUNT(EventType) as Clicks
FROM Data 

WHERE EventType IN ('0','0p','n','np','c') 
GROUP BY crId;

:) 让自己朝着正确的方向前进 ;)

sqlfiddle 演示

select id, crid, 
 count(case when type <> 'c' 
       then crid end) count_others,
 count(case when type ='c' 
       then crid end) count_c
 from tb
 group by crid
 ;
于 2013-01-11T14:25:03.127 回答