我有以下查询:
SELECT year_week FROM web_details where location = ''JF'' AND property_id = ''FARM''
产生以下结果。
YEAR_WEEK
201035
201036
201037
201039
201041
201044
201045
201048
我真正想要的是产生一组结果,只有在连续值可用时才显示值 - 因此产生以下结果......
YEAR_WEEK
201035
201036
201044
任何人都知道如何做到这一点?感谢
从这里得到一点帮助,得到答案。感谢
SELECT year_week FROM web_details w
WHERE location = ''JF'' AND property_id = ''FARM'' AND EXISTS (
SELECT * FROM web_details
WHERE location = ''JF'' AND property_id = ''FARM''
AND cast(year_week as numeric) = cast(w.year_week as numeric) + 1
)
答案 0 :(得分:1)
SELECT year_week
FROM web_details w
WHERE location = ''JF''
AND property_id = ''FARM''
AND EXISTS (
SELECT * FROM web_details
WHERE location = ''JF''
AND property_id = ''FARM''
AND year_week = w.year_week + 1
)
答案 1 :(得分:0)
SELECT year_week
FROM web_details
where location = ''JF''
AND property_id = ''FARM''
AND year_week + 1 IN ( SELECT year_week
FROM web_details
where location = ''JF''
AND property_id = ''FARM''
)
答案 2 :(得分:0)
SELECT
CAST(year_week AS NUMERIC) as year_week
FROM
web_details wd
WHERE
EXISTS(
SELECT
year_week
FROM
web_details wd2
WHERE
wd2.year_week = CASE(RIGHT(wd.year_week, 2))
WHEN '48' THEN CAST((CAST(LEFT(wd.year_week,4) AS INT) + 1) AS VARCHAR(4)) + '01'
ELSE LEFT(wd.year_week,4) + CAST((CAST(RIGHT(wd.year_week,2) AS INT) + 1) AS VARCHAR(2))
END
)
答案 3 :(得分:0)
初稿,可能需要进行一些调整,具体取决于日期的处理方式(一周开始的时间,一年中的第一周等)。年终验证也出现在最后使用的行中。
DECLARE @web_details TABLE (year_week VARCHAR(8))
INSERT INTO @web_details (year_week) VALUES ('201035')
INSERT INTO @web_details (year_week) VALUES ('201036')
INSERT INTO @web_details (year_week) VALUES ('201037')
INSERT INTO @web_details (year_week) VALUES ('201039')
INSERT INTO @web_details (year_week) VALUES ('201041')
INSERT INTO @web_details (year_week) VALUES ('201044')
INSERT INTO @web_details (year_week) VALUES ('201045')
INSERT INTO @web_details (year_week) VALUES ('201048')
INSERT INTO @web_details (year_week) VALUES ('201052')
INSERT INTO @web_details (year_week) VALUES ('201101')
DECLARE @results TABLE (year_week VARCHAR(8), year_week_datetime DATETIME, n INT)
INSERT INTO @results (year_week, year_week_datetime, n)
SELECT
year_week,
DATEADD(week,
CAST(SUBSTRING(year_week, 5, 2) AS INT) - 1,
CAST(SUBSTRING(year_week, 1, 4) + '/1/1' AS DATETIME)
),
ROW_NUMBER() OVER(ORDER BY year_week) AS n FROM @web_details
SELECT
t1.year_week
FROM
@results AS t1 JOIN @results AS t2 ON t1.n + 1 = t2.n
WHERE
DATEDIFF(week, t1.year_week_datetime, t2.year_week_datetime) = 1