这里的SQL - 计算一个不同的列

时间:2016-07-29 00:35:25

标签: mysql sql

试图解决这个问题。

名为users的SQL表包含有关用户的数据。它包含idfirstnamelastnameregisterdate列(其类型为DATE)。编写一个查询,返回每天都注册了名字“Sally”的用户数。*

这是我尝试过的。

Use database
select count (firstname), registerdate 
from users
where firstname = 'Sally' ; 

3 个答案:

答案 0 :(得分:1)

create table userReg
(   id int auto_increment primary key,
    firstname varchar(100) not null,
    lastname varchar(100) not null,
    registerdate date not null
);
truncate userReg;
insert userReg (firstname,lastname,registerdate) values
('Ken','last','2016-01-02'),
('Sally','Higgins','2016-02-02'),
('Sally','Smith','2016-02-02'),
('Sally','Jones','2016-02-04'),
('Sal','lastname','2016-02-07'),
('Jason','last','2016-02-07'),
('Sally','Johnson','2016-04-04');

显示为1行1列总计:

select count(distinct registerdate) as theCount 
from userReg where firstname='Sally'; 
+----------+
| theCount |
+----------+
|        3 |
+----------+

按日期显示:

select registerdate,count(*) as theCount  
from userReg where firstname='Sally' group by registerdate; 
+--------------+----------+
| registerdate | theCount |
+--------------+----------+
| 2016-02-02   |        2 |
| 2016-02-04   |        1 |
| 2016-04-04   |        1 |
+--------------+----------+

distinct内使用count()。 Sally注册有3个不同的日期。

答案 1 :(得分:0)

SELECT Count(id)FROM users    WHERE firstname ='莎莉'    GROUP BY registerdate

答案 2 :(得分:0)

选择DATE_FORMAT(registerdate,'%Y-%m-%d')作为dt,count(id)来自用户,其中firstname ='Sally'group by dt;