在MS SQL 2008中获取数据

时间:2013-08-13 07:09:19

标签: sql sql-server

我有三张表,如:

table1
 id,
 created_Date

table2
 id
 district_ID
 status_ID

table3
 district_ID
 district_Name

现在我需要以下格式的记录

Srno  District_name     <10 days        >10 and <20 days       >20 days

1     xxx               12               15                    20
2     yyy               8                0                     2

根据当前日期计算天数

例如:如果创建的日期是10-08-2013,当前日期是13-08-2013,那么日期差异将为3

那么我的查询应该是什么?任何建议将不胜感激。

谢谢

table1

id      created_Date
1       2013-07-12 13:32:10.957
2       2013-07-12 13:32:10.957
3       2013-08-01 10:00:10.957
4       2013-08-10 13:32:10.957
5       2013-08-10 14:32:10.957


table2

id      district_ID   status_id
1       1             3
2       2             3
3       2             7
4       3             4
5       4             3

table1

district_ID    district_Name
1              xxx
2              yyy
3              zzz
4              aaa
5              bbb

2 个答案:

答案 0 :(得分:2)

我想看一下使用DATEDIFFCASE

  

DATEDIFF(Transact-SQL)

     

返回指定datepart的count(有符号整数)   在指定的startdate和enddate之间交叉的边界。

这样的东西
SELECT  District_name,
        SUM(
                CASE 
                    WHEN DATEDIFF(day,created_Date, getdate()) < 10
                        THEN 1
                    ELSE 0
                END
            ) [<10 days],
        SUM(
                CASE 
                    WHEN DATEDIFF(day,created_Date, getdate()) >= 10 AND DATEDIFF(day,created_Date, getdate()) < 20
                        THEN 1
                    ELSE 0
                END
            ) [>10 and <20 days],
        SUM(
                CASE 
                    WHEN DATEDIFF(day,created_Date, getdate()) >= 20
                        THEN 1
                    ELSE 0
                END
            ) [>20 days]
FROM    Your_Tables_Here
GROUP BY    District_name

答案 1 :(得分:0)

;with cte as (
    select t3.district_Name, datediff(day, t1.created_Date, getdate()) as diff
    from table1 as t1 as t1
        inner join table2 as t2 on t2.id = t1.id
        inner join table3 as t3 on t3.district_id = t2.district_id
)
select
    district_Name,
    sum(case when diff < 10 then 1 else 0 end) as [<10 days],
    sum(case when diff >= 10 and diff < 20 then 1 else 0 end) as [>=10 and < 20 days],
    sum(case when diff >= 20 then 1 else 0 end) as [>= 20 days]
from cte
group by district_Name