簡體   English   中英

通過添加第二個表的日期並減去SQL中第一個表的結果,根據第二個表中的值創建表視圖

[英]Create a table view depending on values in second table by adding the dates of that table and subtracting the result on first table in SQL

打開以創建視圖或更新查詢。

我有兩個下表。 一個顯示拘留,另一個顯示對學生的開始拘留限額。 兩個表都包含行ID作為主鍵。 以下ID不是PK。

      Table1: Detention                        |     Table2: TotalDetention
--------------------------------------------------------------------
PK  ID    startDate    endDate     status      |   PK    ID    totalDetention
1    1   2016-09-23   2016-09-29   Pending     |   1     1          28
2    2   2016-09-23   2016-09-29   Pending     |   2     2          28
3    3   2016-09-23   2016-09-29   Declined    |   3     3          28
4    1   2016-10-01   2016-10-05   Declined    |   4     10         28
5    1   2016-10-05   2016-10-10   Pending     |

當“拘留”狀態設置為“已批准”時,我想從startDate和endDate獲取總天數,然后從TotalDetention中減去該數字(如果可能)。

結果看起來像這樣。

      Table1: Detention                        |     Table2: TotalDetention
--------------------------------------------------------------------
PK  ID    startDate    endDate     status      |   PK    ID    totalDetention
1    1   2016-09-23   2016-09-29   Approved    |   1     1          17
2    2   2016-09-23   2016-09-29   Pending     |   2     2          28
3    3   2016-09-23   2016-09-29   Declined    |   3     3          28
4    1   2016-10-01   2016-10-05   Declined    |   4     10         28
5    1   2016-10-05   2016-10-10   Approved    |

您應該嘗試這樣的事情:

SELECT 
    D.Id
    ,TD.TotalDetention - DATEDIFF(d, D.StartDate, D.EndDate) AS LeftOverDetention
FROM Detention D
INNER JOIN 
TotalDetention TD ON TD.Id = D.Id
WHERE D.status = 'Approved'

然后在UPDATE語句中使用它。 或嘗試一下。

UPDATE TotalDetention
SET TotalDetention = TotalDetention - DATEDIFF(d, D.StartDate, D.EndDate)
FROM TotalDetention TD
INNER JOIN
Detention D
ON D.Id = TD.Id
WHERE D.Status = 'Approved'

根據問題評論中提供的更新,我認為您需要這樣做:

SELECT 
    TD.Id
    ,TD.TotalDetention - isnull(D.Detained, 0) AS LeftOverDetention
FROM TotalDetention TD
LEFT JOIN 
(
    SELECT 
        Id
        ,SUM(DATEDIFF(d, startDate, endDate)) Detained
    FROM Detention
    WHERE status = 'Approved'
    GROUP BY Id
) AS D ON D.Id = TD.Id

忘了加入條件。 我的錯 :(

嘗試這個:

SELECT t.*, t1.id, CASE WHEN t.status = 'Approved' THEN 
(totalDetention-DATEDIFF(dd, startDate, endDate)) 
ELSE 
    totalDetention 
END totalDetention
FROM table1 t
INNER JOIN table2 t1 ON t1.id = t.id 

根據您的標題(更新表格)..您可以在table1上使用更新觸發器來執行此操作。

create trigger updatedata
    on dbo.table1
    after update as
    begin
  if (update(status)) and exists(select * from inserted where status='approved')
    Begin
    update t2
    set t2.totaldetention=t2.totaldetention-datediff(day,i.startddate,i.enddate)
    from table2 t2
    join
    inserted i
    on i.id=t2.id and i.status='approved'

    end
    end

暫無
暫無

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

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