2019/11/28(Thu) 09:12:52 編集(投稿者)
■No93197 (kiku さん) に返信
すみません結果は以下のようになります。
NO NAME ID NAME2 NO2
1.5 b 1 b 2
1.5 b 2 c 1
1.5 b 2 d 2
2.0 a 2 c 1
2.0 a 2 d 2
2.0 a 2 e 3
2.0 a 2 f 4
力ずくでやってみると以下のようになりました。
もっと簡単にできればいいのですが方法はありますでしょうか?
WITH
TB1 (NO, NAME) AS (
SELECT 2, 'a'
UNION SELECT 1.5, 'b'
),
TB2 (ID, NAME, NO2) AS (
SELECT 1, 'a', 1
UNION SELECT 1, 'b', 2
UNION SELECT 2, 'c', 1
UNION SELECT 2, 'd', 2
UNION SELECT 2, 'e', 3
UNION SELECT 2, 'f', 4
),
TB AS (
SELECT TB1.NO, TB1.NAME, TB2.ID, TB2.NAME AS NAME2, TB2.NO2
FROM TB1
INNER JOIN TB2
ON CEILING(TB1.NO) = TB1.NO AND TB1.NO = TB2.ID
OR CEILING(TB1.NO) <> TB1.NO AND (TB2.ID = CEILING(TB1.NO) OR TB2.ID = FLOOR(TB1.NO))
),
TBM AS (
SELECT *,
(
SELECT MIN(ID)
FROM TB AS TB1
WHERE TB1.NO = TB.NO
) AS MINID
,
(
SELECT MAX(ID)
FROM TB AS TB1
WHERE TB1.NO = TB.NO
) AS MAXID
FROM TB
),
TBD AS (
SELECT *,
(
SELECT COUNT(*)
FROM TBM AS TBM1
WHERE TBM1.ID = MINID
AND TBM1.NO = TBM.NO
) AS MINCNT,
(
SELECT COUNT(*)
FROM TBM AS TBM1
WHERE TBM1.ID = MAXID
AND TBM1.NO = TBM.NO
) AS MAXCNT
FROM TBM
)
SELECT NO, NAME, ID, NAME2, NO2
FROM TBD
WHERE CEILING(TBD.NO) = TBD.NO
OR CEILING(TBD.NO) <> TBD.NO
AND (
TBD.ID = MINID AND TBD.NO2 >= TBD.MAXCNT / 2
OR TBD.ID = MAXID AND TBD.NO2 <= TBD.MAXCNT / 2
)