PHP MySQL 分组问题
我的表中有一个列:tbl_customers
,它将客户记录区分为 LEAD 或 CUS。
该列很简单:recordtype
,其中是一个 char(1)。我用 C 或 L 填充它。 显然C=客户,而L=领导者。
我想运行一个按记录创建日期分组的查询,因此我有一个名为:datecreated
的列。
这是我对分组感到困惑的地方。
我想显示结果(在一个查询中)特定日期或日期范围的客户计数和潜在客户计数。我成功地仅提取了 recordtype
:C 或 recordtype
:L 的数字,但这需要 2 个查询。
这是我到目前为止所得到的:
SELECT COUNT(customerid) AS `count`, datecreated
FROM `tbl_customers`
WHERE `datecreated` BETWEEN '$startdate."' AND '".$enddate."'
AND `recordtype` = 'C'
GROUP BY `datecreated` ASC
正如预期的那样,这显示 2 列(客户记录的计数和创建日期
)。
有没有一种方法可以在一个查询中显示两者,同时仍然按 datecreated
列进行分组?
I have a column inside my table: tbl_customers
that distinguishes a customer record as either a LEAD or a CUS.
The column is simply: recordtype
, with is a char(1). I populate it with either C, or L.
Obviously C = customer, while L = lead.
I want to run a query that groups by the day the record was created, so I have a column called: datecreated
.
Here's where I get confused with the grouping.
I want to display a result (in one query) the COUNT of customers and the COUNT of leads for a particular day, or date range. I'm successful with only pulling the number for either recordtype
:C or recordtype
:L , but that takes 2 queries.
Here's what I have so far:
SELECT COUNT(customerid) AS `count`, datecreated
FROM `tbl_customers`
WHERE `datecreated` BETWEEN '$startdate."' AND '".$enddate."'
AND `recordtype` = 'C'
GROUP BY `datecreated` ASC
As expected, this displays 2 columns (the count of customer records and the datecreated
).
Is there a way to display both in one query, while still grouping by the datecreated
column?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以对多个列进行分组。
You can do a group by with over multiple columns.
请参阅 是否可以计算其中的两列相同的查询
See Is it possible to count two columns in the same query
有两种解决方案,具体取决于您想要将两个计数放在单独的行中还是单独的列中。
在单独的行中:
在单独的列中(这称为旋转表格)
There are two solutions, depending on whether you want the two counts in separate rows or in separate columns.
In separate rows:
In separate colums (this is called pivoting the table)
使用:
需要填写日期格式 - 参见STR_TO_DATE 了解详细信息。
Use:
You need to fill out the date format - see STR_TO_DATE for details.