我试图在主查询中获取最小日期值作为列,其中主查询和子查询具有内部联接,并且最小日期值取决于主查询联接中3列的分组
我在主查询Select语句中尝试了子查询,但是正如我的研究显示的那样,它们仅执行一次。我尝试了各种连接方式,但是无法获得逻辑或语法。我认为将cte组合使用可能有效,但无法弄清(对于那些学习新技巧的老狗来说,对于这些高级查询而言仍然太新了)
import itertools
list_1 =[[600,700], [500,200], [100,250], [300,100]]
list_2 = [[600,700,"A"], [500,600,"B"], [100,250,"C"]]
res = [l2[2] if (l1 and l2 and l1[:2] == l2[:2]) else False
for l1, l2 in itertools.zip_longest(list_1, list_2)]
print(res) # ['A', False, 'C', False]
到目前为止,我已经给了我每一行的Comp_Date。我需要实现的以便在以后的程序中可以在其他地方使用数据是
DECLARE
@StartBallDate date = '09-05-2009',
@StartLatDate date = '09-05-2009',
@Male int = 1,
@Female int = 4
SELECT T.*, E.StylID, C.PtsFirstRec
FROM dbo.tblPtsPerCompHistory AS T
INNER JOIN
(
SELECT Min(Comp_Date) PtsFirstRec, Competition_Idx
FROM tblCompetitions
GROUP BY Comp_Date, Competition_Idx
) C ON C.Competition_Idx = T.PtsCompID
INNER JOIN tblEvtStructure AS E ON E.EvtStruct_Idx = T.PtsStructID
WHERE E.SectnID Not Between 9 And 10 And (T.PtsMale = @Male Or T.PtsFemale = @Female And E.StylID = 1 And PtsFirstRec >= @StartBallDate) Or (T.PtsMale = @Male Or T.PtsFemale = @Female And E.StylID = 2 And PtsFirstRec >= @StartLatDate)
所以我所有行都是Ptsmale或PtsFemale,但最小日期值PtsFirstRec是配对的最早日期,也由E.StylID分组
答案 0 :(得分:0)
这是另一个窗口函数:
DECLARE
@StartBallDate date = '09-05-2009',
@StartLatDate date = '09-05-2009',
@Male int = 1,
@Female int = 4
SELECT T.*, E.StylID, MIN(C.PtsFirstRec) OVER (PARTITION BY T.PtsMale T.PtsFemale, E.StylID ORDER BY C.Comp_Date ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) [NewValue]
FROM dbo.tblPtsPerCompHistory AS T
INNER JOIN
(
SELECT Min(Comp_Date) PtsFirstRec, Competition_Idx
FROM tblCompetitions
GROUP BY Comp_Date, Competition_Idx
) C ON C.Competition_Idx = T.PtsCompID
INNER JOIN tblEvtStructure AS E ON E.EvtStruct_Idx = T.PtsStructID
WHERE E.SectnID Not Between 9 And 10 And (T.PtsMale = @Male Or T.PtsFemale = @Female And E.StylID = 1 And PtsFirstRec >= @StartBallDate) Or (T.PtsMale = @Male Or T.PtsFemale = @Female And E.StylID = 2 And PtsFirstRec >= @StartLatDate)
如果您包括测试数据,我们将能够确保代码确实可以正常工作。但这应该符合这些原则。