Sql Server,选择任何一天某个位置的用户数

时间:2013-06-17 08:17:59

标签: sql sql-server-2008

我有以下表格:

表A:

[Location]    [TotalUsers] 
LocationA     5
LocationB     10
LocationC     6

表B:

[User]        [FromLocation] [ToLocation] [StartDate] [EndDate] 
UserA         LocationA      LocationB    01/01/2013  05/05/2013
UserB         LocationB      LocationC    02/02/2013  04/04/2013

我还有一个可能有帮助的日历表。

我想要做的是对于日历表查询表B中的每个日期,给出一个在任何给定日期每个站点有多少用户的计数。 Alos使用表A中的总用户数,我可以每天都有一个totoal。

理想情况下,结果数据集的格式为:

[Date]           [LocationA]  [LocationB]  [LocationC]
01/01/2012       5            10           4

或者

[Date]           [Location]  [UserCount]
01/01/2012       LocationA    10
01/01/2012       LocationB    10
01/01/2012       LocationC    10

如果需要,我可以提供更多细节。

1 个答案:

答案 0 :(得分:0)

表A

LOCATION    TOTAL_USERS
LOCATION_A  5
LOCATION_B  10
LOCATION_C  6

表B

USER    FROM_LOCATION   TO_LOCATION START_DATE  END_DATE
User_A  LOCATION_A  LOCATION_B  2013-01-01  2013-05-05 
User_B  LOCATION_B  LOCATION_C  2013-02-02  2013-04-04 

查询

DECLARE @DATE_TO_QUERY datetime = '01/01/2013'


SELECT 
    DATE_TO_QUERY, LOCATION_A, LOCATION_B, LOCATION_C
FROM (

SELECT 
    A.TOTAL_USERS,
    @DATE_TO_QUERY AS DATE_TO_QUERY,
    A.LOCATION
FROM TableA A
INNER JOIN TableB B
ON A.LOCATION = B.FROM_LOCATION
OR A.LOCATION = B.TO_LOCATION
WHERE DATEDIFF(DD, START_DATE, @DATE_TO_QUERY) >= 0
AND DATEDIFF(DD, @DATE_TO_QUERY, END_DATE) >= 0

) up
PIVOT (SUM(TOTAL_USERS) FOR  LOCATION IN (LOCATION_A, LOCATION_B, LOCATION_C)) AS pvt

以上查询的结果

DATE_TO_QUERY LOCATION_A    LOCATION_B  LOCATION_C
2013-01-01     5              10             NULL