0

我有三个表,如下所示:

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
4

2 回答 2

2

我会看看使用DATEDIFFCASE

DATEDIFF (Transact-SQL)

返回指定开始日期和结束日期之间跨越的指定日期部分边界的计数(有符号整数)。

就像是

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
于 2013-08-13T07:19:06.837 回答
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
于 2013-08-13T07:22:36.570 回答