我有一个包含union all
查询的视图,并返回如下所示的结果:
CREATE VIEW [dbo].[MANU_TEST]
AS
SELECT DISTINCT
PT.PRODUCT AS PRODUCT, PT.TEXT_CODE AS TEXT_CODE,
PHT.PHRASE AS F_PHRASE,PHT.LANGUAGE
FROM
PRODUCT_TEXT PT
LEFT JOIN
PHRASE_LINK PHL ON PT.TEXT_CODE = PHL.TEXT_CODE
INNER JOIN
PHRASE_TRANSLATIONS PHT ON PHL.PHRASE_ID = PHT.PHRASE_ID
WHERE
PT.DATA_CODE = 'MANU' AND PHT.LANGUAGE = 'EN'
UNION ALL
SELECT DISTINCT
PT.F_ALIAS AS PRODUCT, PT.TEXT_CODE AS TEXT_CODE,
PHT.PHRASE AS F_PHRASE,PHT.LANGUAGE
FROM
PROD_ALIAS_TEXT PT
LEFT JOIN
PHRASE_LINK PHL ON PT.TEXT_CODE = PHL.TEXT_CODE
INNER JOIN
PHRASE_TRANSLATIONS PHT ON PHL.PHRASE_ID = PHT.PHRASE_ID
WHERE
PT.DATA_CODE = 'MANU' AND PHT.LANGUAGE = 'EN'
输出:
F_PRODUCT F_TEXTCODE F_PHRASE F_LANGUAGE
-----------------------------------------------------
A MANU001 TEST1 EN
A MANU002 TEST2 EN
我从上方的视图创建了另一个视图,并使用东西在下方的输出中显示。
CREATE VIEW [dbo].[MANU_STUFFED]
AS
SELECT
V1.F_PRODUCT, v1.F_LANGUAGE,
F_TEXT_CODES = STUFF((SELECT DISTINCT ',' + V2.F_TEXT_CODE
FROM MANU_TEST V2
WHERE V1.F_PRODUCT = V2.F_PRODUCT
FOR XML PATH('')), 1, 1, ''),
F_PHRASES = STUFF((SELECT DISTINCT ' |par ' + V3.F_PHRASE
FROM MANU_TEST V3
WHERE V1.F_PRODUCT = V3.F_PRODUCT
FOR XML PATH('')), 1, 5, '')
FROM
MANU_TEST V1
GROUP BY
V1.F_PRODUCT, V1.F_LANGUAGE
输出:
F_PRODUCT F_LANGUAGE F_TEXTCODES, F_PHRASES
-------------------------------------------------------------
A EN MANU001,MANU002 TEST1 |par TEST2
它正在工作,但是可以在单个视图中将以上两个查询合并为一个查询吗?
答案 0 :(得分:1)
当然。您可以在视图中使用CTE:
CREATE VIEW [dbo].[MANU_STUFFED] AS
WITH MANU_TEST AS (
SELECT . . .
)
SELECT . . .;
. . .
是您现有的查询。