0

我有以下表格:

表 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 使用 Table AI 中的总用户数可以得出每天的总数。

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

[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

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

4

1 回答 1

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
于 2013-06-17T09:17:08.740 回答