문제

I searched forum for 1h and didn't find nothing similar.

I have this problem: I want to compare two colums ID and DATE if they are the same in both tables i want to put number from table 2 next to it. But if it is not the same i want to fill yearly quota on the date. I am working in Access.

table1

id|date|state_on_date 
1|30.12.2013|23 
1|31.12.2013|25 
1|1.1.2014|35
1|2.1.2014|12 
2|30.12.2013|34 
2|31.12.2013|65 
2|1.1.2014|43 

table2

id|date|year_quantity 
1|31.12.2013|100 
1|31.12.2014|150 
2|31.12.2013|200 
2|31.12.2014|300 

I want to get:

table 3

id|date|state_on_date|year_quantity
1|30.12.2013|23|100
1|31.12.2013|25|100 
1|1.1.2014|35|150 
1|2.1.2014|12|150 
2|30.12.2013|34|200 
2|31.12.2013|65|200 
2|1.1.2014|43|300 

I tried joins and reading forums but didn't find solution.

도움이 되었습니까?

해결책

Are you looking for this?

SELECT id, date, state_on_date,
(
  SELECT TOP 1 year_quantity
    FROM table2
   WHERE id = t.id
     AND date >= t.date
   ORDER BY date
) AS year_quantity
  FROM table1 t

Output:

| ID |       DATE | STATE_ON_DATE | YEAR_QUANTITY |
|----|------------|---------------|---------------|
|  1 | 2013-12-30 |            23 |           100 |
|  1 | 2013-12-31 |            25 |           100 |
|  1 | 2014-01-01 |            35 |           150 |
|  1 | 2014-01-02 |            12 |           150 |
|  2 | 2013-12-30 |            34 |           200 |
|  2 | 2013-12-31 |            65 |           200 |
|  2 | 2014-01-01 |            43 |           300 |

Here is SQLFiddle demo It's for SQL Server but should work just fine in MS Accesss.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top