我有一個表statistic。該表有step_index,例如1、2、3和4。我需要使查詢添加week2和total_request2,其中week是37,并以相同的step_index連接自己的表。
示例:
step_index|type |year|week|total_request|
---------- -------- ---- ---- -------------
1|爆破|2021| 38| 1|
2|爆破|2021| 38| 1|
3|爆破|2021| 38| 1|
4|爆破|2021| 38| 1|
1|爆破|2021| 37| 6|
2|爆破|2021| 37| 6|
3|爆破|2021| 37| 6|
4|爆破|2021| 37| 6|
結果應該是:
step_index|type |year| 操作員">|周|總請求|周2|總請求2|
---------- -------- ---- ---- ------------- ----- --------------
1|爆破|2021| 38| 1| 37| 6 |
2|爆破|2021| 38| 1| 37| 6 |
3|爆破|2021| 38| 1| 37| 6 |
4|爆破|2021| 38| 1| 37| 6 |
我嘗試了行內和with子句,但是沒有得到week2和total_request2的結果。
uj5u.com熱心網友回復:
基于你提供的內容,這是我對你想要什么的最佳猜測。 如果你能澄清主鍵和一些關于你正在尋找的更具體的資訊,我可以把我的查詢修改得更好。
select s.step_index
,s.type
,s.year
,s.week
,s.total_request
,s2.week
,s2.total_request2
from statistic s
,統計學s2
where s2.week = 37
and s2.step_index = s.step_index
and s.week = 38
uj5u.com熱心網友回復:
WITH CTE(STEP_INDEX,TYPE,YEAR, WEEK, TOTAL_REQUEST) AS
(
SELECT 1,'BLASTING', 2021, 38,1 UNION ALLSELECT 2,'BLASTING',2021, 38,1 UNION ALLSELECT 3,'BLASTING',2021, 38,1 UNION ALLSELECT 4,'BLASTING',2021, 38,1 UNION ALLSELECT 1,'BLASTING',2021, 37,6 UNION ALLSELECT 2,'BLASTING',2021, 37,6 UNION ALLSELECT 3,'BLASTING',2021, 37,6 UNION ALLSELECT 4,'BLASTING', 2021,37,6)
)
SELECT C.STEP_INDEX,C.TYPE,C.YEAR,C.WEEK,C.TOTAL_REQUEST。
X.WEEK AS WEEK_2,X.TOTAL_REQUEST AS TOTAL_REQUEST_2
FROM CTE AS C
LEFT JOIN LATERALSELECT C2.STEP_INDEX,C2.TYPE,C2.YEAR,C2.WEEK,C2.TOTAL_REQUEST
FROM CTE AS C2
WHERE C.STEP_INDEX=C2.STEP_INDEX AND C。 周-1=C2.WEEK AND C.YEAR=C2.YEAR
)X ON TRUE
WHERE C.YEAR=2021 AND C.WEEK=38
基于你的樣本資料
uj5u.com熱心網友回復:
你可以將其作為一個明確的JOIN。 正確的語法是:
select s.step_index, s.type, s.year, s.week, s.total_request。
s2.week as week2, s2.total_request as total_request2
from統計學s join
統計資訊s2
on s2.year = s.year and
s2.step_index =s.step_index and
s2.星期 = 37 and
s.week = 38
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/322151.html
標籤:
