簡體   English   中英

如何從此表中正確提取記錄?

[英]How to correctly extract records from this table?

我有一個帶有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      |

 
 
 
  
  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

終於我找到了適合我的解決方案:

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM