如何从行中的联接表而不是相邻列中获取列

时间:2019-06-17 07:35:51

标签: sql sql-server

我有两个表PRODUCT和PRODUCTMODEL。可以使用PRODUCTMODELID加入它们。我想获得一个输出,以使PRODUCTMODEL表中的行位于PRODUCT表FOR EACH PRODUCT的行之下。

输出必须在平面文件中。我可以照顾平面文件的内容。我想要一些指示以行而不是列的方式获取联接数据。

CREATE TABLE [PRODUCT](
    [PRODUCTID] [INT] NOT NULL,
    [PRODUCTMODELID] [INT],
    [NAME] [DBO].[NAME] NOT NULL,
    [PRODUCTNUMBER] [NVARCHAR](25) NOT NULL,
)

CREATE TABLE [PRODUCTMODEL](
    [PRODUCTMODELID] [INT] NOT NULL,
    [NAME] [NVARCHAR](25) NOT NULL
)

INSERT INTO PRODUCTMODEL (PRODUCTMODELID, NAME)
VALUES (11, 'LONG-SLEEVE LOGO JERSEY')

INSERT INTO PRODUCT (PRODUCTID, PRODUCTMODELID, NAME, PRODUCTNUMBER)
VALUES (713, 11, 'LONG-SLEEVE LOGO JERSEY', 'LJ-0192-S')

INSERT INTO PRODUCT (PRODUCTID, PRODUCTMODELID, NAME, PRODUCTNUMBER)
VALUES (714, 11, 'LONG-SLEEVE LOGO JERSEY', 'LJ-0192-M')

INSERT INTO PRODUCT (PRODUCTID, PRODUCTMODELID, NAME, PRODUCTNUMBER)
VALUES (715, 11, 'LONG-SLEEVE LOGO JERSEY', 'LJ-0192-L')

INSERT INTO PRODUCT (PRODUCTID, PRODUCTMODELID, NAME, PRODUCTNUMBER)
VALUES (716, 11, 'LONG-SLEEVE LOGO JERSEY', 'LJ-0192-X')

预期输出为:

|PRODUCT|713|LONG-SLEEVE LOGO JERSEY|LJ-0192-S|
|MODEL|11|Long-Sleeve Logo Jersey|
|PRODUCT|714|LONG-SLEEVE LOGO JERSEY|LJ-0192-M|
|MODEL|11|Long-Sleeve Logo Jersey|
|PRODUCT|715|LONG-SLEEVE LOGO JERSEY|LJ-0192-L|
|MODEL|11|Long-Sleeve Logo Jersey|
|PRODUCT|716|LONG-SLEEVE LOGO JERSEY|LJ-0192-X|
|MODEL|11|Long-Sleeve Logo Jersey|

3 个答案:

答案 0 :(得分:1)

尝试使用交叉应用

;WITH CTE AS 
(
SELECT CONCAT('|PRODUCT|',P.PRODUCTID,'|',P.NAME,'|',P.PRODUCTNUMBER,'|') AS Col1,
        CONCAT('|MODEL|',PM.PRODUCTMODELID,'|',PM.NAME+'|') AS COl2       
 FROM [PRODUCT] P
 INNER JOIN [PRODUCTMODEL] PM
    ON PM.PRODUCTMODELID = P.PRODUCTMODELID
 )
 SELECT Result 
 FROM CTE
 CROSS APPLY (VALUES (Col1,'Col1'),(Col2,'Col2')
              )DT (Result,Names)

结果

|PRODUCT|713|LJ-0192-S|
|MODEL|11|LONG-SLEEVE LOGO JERSEY|
|PRODUCT|714|LJ-0192-M|
|MODEL|11|LONG-SLEEVE LOGO JERSEY|
|PRODUCT|715|LJ-0192-L|
|MODEL|11|LONG-SLEEVE LOGO JERSEY|
|PRODUCT|716|LJ-0192-X|
|MODEL|11|LONG-SLEEVE LOGO JERSEY|

答案 1 :(得分:1)

;
WITH temp
AS (SELECT
  'Product' AS Type,
  CAST([PRODUCTID] AS varchar(10)) AS PID,
  [PRODUCTMODELID],
  [PRODUCTNUMBER],
  CAST(productModelid AS varchar(10)) + '_1' AS DOrder
FROM Product

UNION

SELECT
  'Model' AS Type,
  '' AS PID,
  [PRODUCTMODELID],
  '' AS ProductNumber,
  Name,
  CAST(productModelid AS varchar(10)) + '_2' AS DOrder
FROM PRODUCTMODEL)

SELECT
  *
FROM temp
ORDER BY dOrder

答案 2 :(得分:1)

您可以尝试在子查询中使用JOIN或在CTE中使用CROSS APPLY的值来制作UNION ALL

;WITH CTE AS (
    SELECT p.PRODUCTMODELID PRODUCTMODELID,
           p.NAME pName,
           pm.Name pmName,
           PRODUCTID,
           PRODUCTNUMBER
    FROM PRODUCT p JOIN PRODUCTMODEL pm 
    ON pm.PRODUCTMODELID =p.PRODUCTMODELID
)
SELECT v.*
FROM CTE CROSS APPLY (
    VALUES 
    ('PRODUCT',pmName,PRODUCTID,PRODUCTNUMBER),
    ('MODEL',pName,PRODUCTMODELID,'')
) v (col1,col2,col3,col4)

sqlfiddle