
[英]How to Count the number of Countries From registered users in my users table
[英]how to write SQL to count the number of mobile/tablet/desktop users?
我有一张桌子,
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输出mobile / desktop / 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查询吗?
您有一个正确的想法,但是,正如您所看到的,这是无效的语法。 您可以使用一个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
您应该使用SUM
代替COUNT
,因为其中的条件为true时返回1,而当条件为false时返回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函数将不考虑这一点。
您可以尝试像:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.