0

我有一个带有DATE字段的关联表:

|       DATE          |  USER_ID  | GROUP_ID   |
| 2012-09-20 00:00:00 |     7     |     1      |
| 2012-09-20 00:00:00 |     6     |     1      |
| 2012-09-13 00:00:00 |     5     |     1      |
| 2012-09-10 00:00:00 |     1     |     1      |
| 2012-09-02 00:00:00 |     5     |     3      |
| 2012-08-02 00:00:00 |     5     |     2      |
| 2012-07-01 00:00:00 |     5     |     1      |
| 2012-07-01 00:00:00 |     3     |     1      |

每条记录代表一个用户和一个组之间的关联。每个关联从表中指示的日期开始有效,并保持不变,直到在表中插入新的关联。

要知道某个日期的用户组关联非常简单:只需选择最大日期 <= 比指定日期。

但现在我需要提取与某个日期范围内的某个组关联的所有用户。提供的参数是:group_iddate_fromdate_to

我必须用 Linq 来实现它,但我正在尝试使用 T-SQL 测试该过程。

这就是我尝试过的:

SELECT *
FROM user_group
where group_id = 1
and '2012-09-11' <= date
and date <= '2012-09-20'
UNION
SELECT TOP 1 *
FROM user_group
where group_id = 1
and date <= '2012-09-11'
order by date desc

但显然它不起作用......

笔记:

主要困难是在from_date之前创建关联但仍然有效。为了清楚起见,我需要得到这个结果:

|       DATE          |  USER_ID  | GROUP_ID   |
| 2012-09-20 00:00:00 |     7     |     1      |
| 2012-09-20 00:00:00 |     6     |     1      |
| 2012-09-13 00:00:00 |     5     |     1      |
| 2012-09-10 00:00:00 |     1     |     1      |
| 2012-07-01 00:00:00 |     3     |     1      |
4

2 回答 2

0

select * from user_group where group_id=1 and date<=convert(date,'2012-09-20',120)
except
select * from user_group where group_id=1 and date<=convert(date,'2012-09-11',120)

或者也许这...

select date, user_id, group_id
from
(
    select *, ROW_NUMBER() over (partition by user_id order by date desc) rn 
    from user_group
    where date<=convert(date,'2012-09-20',120)
) v
where rn=1
and group_id=1    
order by date desc
于 2012-09-26T08:19:38.453 回答
0

最后我找到了这个对我有用的解决方案:

var innerAssoc = from assoc in user_group
                 where assoc.group_id == group_id
                 && dateFrom.Date <= assoc.date.Date
                 && date.Date <= dateTo.Date
                 select assoc;

var outerAssoc = from assoc in user_group
                 where assoc.group_id == group_id
                 && assoc.date.Date == user_group
                 .Where(a => a.user_id == assoc.user_id && a.date.Date <= dateFrom.Date)
                 .Select(a => a.date.Date).Max()
                 select assoc;

var res = innerAssoc.Union(outerAssoc);
于 2012-09-26T09:40:58.497 回答