这里我有两个CTE,我需要从这两个CTE中选择值作为单个查询。我可以一次从单个CTE中选择值,但我不知道如何合并这两个CTE并从CTE中选择值。
在下面的查询中,我可以从第二个CTE中选择值
DECLARE @now DateTime;
DECLARE @Firstweekstart DateTime;
DECLARE @FirstweekEnd DateTime;
SET @now = CONVERT(datetime, CONVERT(date,getdate()));
SET @Firstweekstart = DATEADD(
DD,
-(DATEPART(DW, @now - 7) - 1),
@now - 7);
SET @Firstweekstart = dateadd(ms, -1, @Firstweekstart)
SET @Firstweekend = DATEADD(
DD,
7 - (DATEPART(DW, @now - 7)),
@now - 7);
SET @Firstweekend = dateadd(ms, -3, @Firstweekend+1)
;WITH CTE1 AS
(
SELECT CHINFO.CHILDID,CHINFO.CONSUMERID,
DATEADD(DD, -(DATEPART(DW, CHINFO.Adddate)-1), CHINFO.Adddate) AS APPLICATIONUSAGESTARTDATE,
DATEDIFF(WW,CHINFO.Adddate,@now) AS WEEKNUMBER,
ROW_NUMBER() OVER
(PARTITION BY CHINFO.CHILDID ORDER BY CHINFO.Adddate ASC) AS RN
FROM BKA.CHILDINFORMATION CHINFO
LEFT OUTER JOIN BKA.CHILDEVENTS CHE
ON CHE.CHILDID = CHINFO.CHILDID
GROUP BY CHINFO.CHILDID,CHINFO.CONSUMERID,CHINFO.Adddate
)
,CTE2 as
(SELECT Distinct CHINFO.CHILDID ,CHE.TIMESTAMP
,ROW_NUMBER() OVER (PARTITION BY CHINFO.CHILDID ORDER BY CHE.TIMESTAMP) row
FROM BKA.CHILDINFORMATION CHINFO
JOIN BKA.CHILDEVENTS CHE
ON CHE.CHILDID = CHINFO.CHILDID
WHERE CHE.TYPE = 'pottybreak'
AND CHE.ADDDATE BETWEEN @Firstweekstart AND @Firstweekend
GROUP BY CHINFO.CHILDID,CHE.TIMESTAMP
)
SELECT
a.CHILDID ,
AVG(CONVERT(DECIMAl,DATEDIFF ( minute , b.TIMESTAMP , a.TIMESTAMP))) as CURRENTWEEKTIMERRESTART
FROM
CTE2 a
LEFT JOIN CTE2 b
on a.CHILDID = b.CHILDID
and a.row = b.row+1
group by a.childid
我需要将以下查询与上面的查询合并
SELECT CTE1.CONSUMERID,
CTE1.CHILDID,
CTE1.APPLICATIONUSAGESTARTDATE,
CTE1.WEEKNUMBER
FROM CTE1
WHERE RN = 1 ORDER BY CTE1.CHILDID ASC
有什么建议吗?
答案 0 :(得分:1)
如果您要根据CTE1
列加入CTE2
和CHILDID
的值,那么您可以写为:
SELECT
CTE1.CONSUMERID,
CTE1.CHILDID,
CTE1.APPLICATIONUSAGESTARTDATE,
CTE1.WEEKNUMBER,
-- a.CHILDID ,
AVG(CONVERT(DECIMAl,DATEDIFF ( minute , b.TIMESTAMP , a.TIMESTAMP)))
as CURRENTWEEKTIMERRESTART
FROM
CTE2 a
LEFT JOIN CTE2 b on a.CHILDID = b.CHILDID and a.row = b.row+1
LEFT JOIN CTE1 on CTE1.CHILDID = a.CHILDID and CTE1.RN = 1
group by CTE1.CONSUMERID,CTE1.CHILDID,CTE1.APPLICATIONUSAGESTARTDATE,CTE1.WEEKNUMBER
ORDER BY CTE1.CHILDID ASC