如何编写sql来统计移动/平板/桌面用户的数量?

r6l8ljro  于 2021-06-17  发布在  Mysql
关注(0)|答案(3)|浏览(348)

我有一张table,

VisitorId   date            deviceType
1           2018-12-11      mobile
2           2018-12-11      mobile
3           2018-12-11      desktop
4           2018-12-11      mobile
1           2018-12-12      desktop
2           2018-12-12      mobile
1           2018-12-20      mobile
2           2018-12-20      tablet
...

每行记录一个新访问者的信息。
我正在尝试编写一个查询,根据日期输出移动/桌面/平板电脑的数量。预期的输出应该如下所示

date        numOfDesktop      numOfTablet      numOfMobile
2018-12-11  1                 0                3
2018-12-12  1                 0                1
2018-12-20  0                 1                1
...

我已经写了这样一个sql,但是语法是错误的。

SELECT 
  date,
  COUNT(deviceType= "mobile") As numOfMobile,
  COUNT(deviceType= "desktop") AS numOfDesktop,
  COUNT(deviceType= "tablet") AS numOfTablet
FROM 
  tableName
GROUP BY date
ORDER BY date ASC

我没有sql方面的经验,有人能帮我设计一个有效的sql查询吗?

fquxozlt

fquxozlt1#

你应该用 SUM 代替 COUNT 当其中的条件为真时,1是返回值,当它为假时,0是返回值,因此对这些值求和就好像是根据条件对它们进行计数一样。你还应该确保日期中没有时间。

SELECT 
  DATE(`date`) `date`,
  SUM(deviceType="mobile") As numOfMobile,
  SUM(deviceType="desktop") AS numOfDesktop,
  SUM(deviceType="tablet") AS numOfTablet
FROM 
  tableName
GROUP BY DATE(`date`)
ORDER BY DATE(`date`);

要使用count,请执行以下操作:

SELECT 
  DATE(`date`) `date`,
  COUNT(IF(deviceType="mobile", 1, NULL)) As numOfMobile,
  COUNT(IF(deviceType="desktop", 1, NULL)) AS numOfDesktop,
  COUNT(IF(deviceType="tablet", 1, NULL)) AS numOfTablet
FROM 
  tableName
GROUP BY DATE(`date`)
ORDER BY DATE(`date`);

在这种情况下,如果条件为false,则返回null,并且count函数不考虑这一点。

jexiocij

jexiocij2#

你的想法是对的,不过,正如你所看到的,这不是有效的语法。你需要一个 case 尽管如此:

SELECT 
  date,
  COUNT(CASE deviceType WHEN 'mobile' THEN 1 END) As numOfMobile,
  COUNT(CASE deviceType WHEN 'desktop' THEN 1 END) AS numOfDesktop,
  COUNT(CASE deviceType WHEN 'tablet' THEN 1 END) AS numOfTablet
FROM 
  tableName
GROUP BY date
ORDER BY date ASC
dzhpxtsq

dzhpxtsq3#

您可以尝试如下方式:

SELECT 
    date,
    sum(deviceType= "desktop") As numOfDesktop,
    sum(deviceType= "tablet") As numOfTablet,
    sum(deviceType = 'mobile') as numOfMobile
FROM 
    tableName
GROUP BY date
ORDER BY date ASC

相关问题