从相同的列到列

时间:2016-08-15 08:29:26

标签: sqlite

我试图从今天,本月和上个月根据当前日期创建的客户表客户计算,所以我尝试了这个

Select * FROM
       (
         (Select count(c1.id) from customers c1 where c1.created = date('now', 'localtime')) d 
         (Select count(id) from customers where created >= date('now','start of month') AND created <= date('now','start of month','+1 month','-1 day')) m
         (Select count(id) from customers where created >= datetime('now', 'start of month') AND created <= date('now', 'localtime')) m
       ) lm

我期待像

这样的事情
d   m   lm
-----------
1   20   15

但是我可以看到正确的做法,我做错了什么?

2 个答案:

答案 0 :(得分:2)

以下是您的查询的工作版本:

SELECT d.n as 'Day', m.n as 'Month', lm.n as 'Last Month' FROM
(SELECT count(id) as `n` FROM `customers` 
 WHERE created >= date('now', 'localtime') 
 AND created <= date('now', 'localtime','+1 day')) d,
(SELECT count(id) as `n` FROM `customers`
 WHERE created >= date('now','start of month')
 AND created <= date('now','start of month','+1 month','-1 day')) m,
(SELECT count(id) as `n` FROM `customers`
 WHERE created >= date('now','start of month','-1 month')
 AND created <= date('now','start of month','-1 day')) lm;

与工作SQLFiddle一起提供一些样本数据。

请注意,选择当天创建的客户的技术将失败,因为您正在比较确切的时间戳与今天的日期。除了午夜之外,这永远不会匹配:

-- Show that checking a DB timestamp against the current
-- date will fail to gather any datapoints (unless the
-- account was created at precisely midnight!)
SELECT count(id) FROM `customers` 
WHERE created = date('now', 'localtime');

答案 1 :(得分:0)

Sqlite 3.7有许多奇怪的错误 1)count(*)和count(singlefield)在嵌套查询中返回不同的结果 2)外部查询不是从表的名称而是从字段的名称获取字段名称(可能它甚至是正确的,但在MSSAL中我期望其他行为) 和你的错误 3)您在选择a,b,c中的值之间错过了逗号 4)lm别名在错误的地方

您的查询将是(当然条件是正确的)

Select * FROM
       (
         (Select count(c1.id) d from customers c1 where c1.created = date('now', 'localtime')) ,
         (Select count(id) m from customers where created >= date('now','start of month') AND created <= date('now','start of month','+1 month','-1 day')) ,
         (Select count(id) lm from customers where created >= datetime('now', 'start of month') AND created <= date('now', 'localtime')) 
       )