sql结合两个查询和截断日期

时间:2010-07-12 21:49:01

标签: sql sqlite pivot

我试图截断日期只能获得年/月而不是年份/月/日的形式。 我想要做的就是计算每月销售的所有汽车以及每个月销售的所有汽车,具体如下:

// counts cars    
select SellDate, count(*) 
from category 
where machineIdentification = 1 
GROUP BY SellDate  

// counts suv's  
select SellDate, count(*) 
from category 
where machineIdentification = 2 
GROUP BY SellDate  

单独运行每个查询给我一个日期列表(y / m / d /到第二个的时间)和数字1,因为只有1辆汽车或suv出售了那个确切的时间,但是我试图通过SellDate进行分组并截断这个日期只显示每个月的总数。

我要做的是组合查询并最终得到如下值:

2009-01 23 10  
2009-02 13 14  
2009-03 29 7  

第一列是year.month,第二列是销售的汽车,第三列是销售的suv

2 个答案:

答案 0 :(得分:2)

select
   date(SellDate, 'start of month'),
   SUM (CASE machineIdentification = 1 THEN 1 ELSE 0 END) AS carcount ,
   SUM (CASE machineIdentification = 2 THEN 1 ELSE 0 END) AS suvcount 
from category 
where machineIdentification IN (1, 2 )
GROUP BY date(SellDate, 'start of month')

我会在客户端代码中连接年/月,以便您可以使用“2010年7月”

(我无法在SQLLite中测试,抱歉,但除了输出年/月格式之外,这应该是关闭的)

答案 1 :(得分:1)

它可能涉及子查询中的联合和日期格式,为SQLLite重新格式化:

SELECT SellDate, COUNT(CARS) AS Cars, COUNT(SUVS) AS SUVS
FROM         
 (SELECT STRFTIME('%Y-%m',SellDate) AS SellDate,
         MachineIdentification AS CARS, null AS SUVS
     FROM          Category
     where machineIdentification = 1 
     UNION
     SELECT STRFTIME('%Y-%m',SellDate) AS SellDate, 
         null AS CARS, MachineIdentification AS SUVS
     FROM Category
     where machineIdentification = 2 
  )
GROUP BY SellDate