用于在一个查询中获取所有结果的SQL查询

时间:2016-03-25 03:11:45

标签: sql-server sql-server-2008

测试数据:

    id  date       company  location  
   ----------------------------------
    1   03/01/2016  ABC      india     
    2   03/25/2016  ABC      us
    3   02/24/2016  ABC      india
    4   02/25/2016  ABC      us
    5   03/02/2016  ABC      india

查询#1

select count(id) 
from table 
where company = 'ABC' 
  and date between 03/01/2016 and 03/31/2016

查询#2

select count(id) 
from table 
where company = 'ABC' 
  and date between 02/01/2016 and 02/29/2016

需要计算当前和前几个月的位置明智计数。 如何在一个查询中编写SQL查询以返回位置,如下所示?

预期结果:

   company currentmonth   Previousmonth   location
    ABC      2                   1          india
    ABC      1                   1           us

2 个答案:

答案 0 :(得分:3)

尝试:

select company,
       sum(case when month(date)=month(getdate()) 
                        then 1 else 0 end) as currentMonth,
       sum(case when month(date)=month(dateadd(MONTH,-1,getdate())) 
                        then 1 else 0 end) as Previuosmonth,
       location 
  from yourTable
 where month(date) between month(dateadd(MONTH,-1,getdate())) and month(getdate())
   AND company='ABC'
 group by company, location

由于您进行了两次查询并使用当前月份(三月)和之前的过滤器进行过滤。我决定使用函数MONTH从系统的当前日期(getdate())中提取月份,然后减去1,这样你将始终拥有当前月份和前一个月。

修改

正如@DhananjayaKuppu所指出的,我解决了当你有一个月为1月时的问题,因为month函数返回一个整数,它会在我的计算中返回0。现在它已修复。

答案 1 :(得分:2)

你可以尝试减去当前日期年份格式(例如:201603)和日期格式的日期格式(例如:201603),如果它结果为0视为当前月,否则上个月,希望它会有所帮助:

SELECT company,
       location,
       sum(iif(d = 0, 0, 1)) cm,
       sum(iif(d = 0, 1, 0)) pm        
FROM (SELECT company, 
       location, 
       CONVERT(INT,
         CONVERT(CHAR(4), GetDate(), 120) + 
         CONVERT(CHAR(2), GetDate(), 101)
       ) -
       CONVERT(INT, 
         CONVERT(CHAR(4), date, 120) + 
         CONVERT(CHAR(2), date, 101)
       )  as d
FROM table) vw
GROUP BY company, location