如何加入这两个查询?(带连接的选择查询和一个unpivot查询)

时间:2012-11-23 01:39:28

标签: sql sql-server sql-server-2008-r2 unpivot

以下是我的两个问题

SELECT EWND.Position,
NKey = CASE WHEN ISNULL(Translation.Name, '') = '' THEN EWND.Name
ELSE  Translation.Name END, Unit = EW_N_DEF.Units                               
FROM EWND
INNER JOIN EW_N_DEF ON EW_N_DEF.Nutr_No = EWND.Nutr_No
LEFT JOIN Translation ON Translation.CodeMain = EWND.Nutr_no
WHERE Translation.CodeTrans  = 1
ORDER BY EWND.Position

这是非正式的

SELECT * 
FROM 
   (SELECT N1,N2,N3,N4,N5,N6,N7,N8,N9,N10,N11,N12,N13,N14,N15,N16,N17,N18,N19,N20,N21,N22,N23,N24,N25,N26,N27,N28,N29,N30,N31,N32,N33,N34
   FROM EWNVal WHERE Code=6035) Test
UNPIVOT
   (Value FOR NUTCODE IN 
      (N1,N2,N3,N4,N5,N6,N7,N8,N9,N10,N11,N12,N13,N14,N15,N16,N17,N18,N19,N20,N21,N22,N23,N24,N25,N26,N27,N28,N29,N30,N31,N32,N33,N34)
)AS test

查询的输出如下:

  Position Name         Unit
    1   Calories    
    2   Protein g
    3   Total Fat           g
    4   Total Carbs         g
    5   Calories from Fat   
    6   Saturated Fat       g
    7   Trans Fat           g
    8   Monounsaturated Fat g
    9   Polyunsaturated Fat g   

并且

Value Code
    0   N1
    0   N2
    0   N3
    0   N4
    0   N5
    0   N6
    0   N7
    0   N8
    0   N9

输出必须像这样

1   Calories                0   N1
2   Protein             g   0   N2
3   Total Fat           g   0   N3
4   Total Carbs         g   0   N4
5   Calories from Fat       0   N5
6   Saturated Fat       g   0   N6
7   Trans Fat           g   0   N7
8   Monounsaturated Fat g   0   N8
9   Polyunsaturated Fat g   0   N9

两个查询都输出相同数量的行而不是列,是否可以加入这两个?我尝试了联盟,但它有问题我无法解决

提前致谢!

2 个答案:

答案 0 :(得分:0)

在Union和Union中,所有结果都必须具有相同的列名。对于列,您可以使用任何别名,但列名必须相同。

你可以参考这个答案

combining results of two select statements

答案 1 :(得分:0)

如果两个查询中的数据可以根据CodePosition的数字部分加入,那么您可以使用以下内容:

select q1.position,
  q1.name,
  q2.value,
  q2.code
from
(
  SELECT EWND.Position,
    NKey = CASE WHEN ISNULL(Translation.Name, '') = '' THEN EWND.Name
                ELSE  Translation.Name END, Unit = EW_N_DEF.Units                               
  FROM EWND
  INNER JOIN EW_N_DEF 
    ON EW_N_DEF.Nutr_No = EWND.Nutr_No
  LEFT JOIN Translation 
    ON Translation.CodeMain = EWND.Nutr_no
  WHERE Translation.CodeTrans  = 1
) q1
full outer join
(
  SELECT value, code
  FROM 
  (
     SELECT N1,N2,N3,N4,N5,N6,N7,N8,N9,N10,N11,N12,N13,N14,N15,N16,N17,N18,N19,N20,N21,N22,N23,N24,N25,N26,N27,N28,N29,N30,N31,N32,N33,N34
     FROM EWNVal 
     WHERE Code=6035
  ) Test
  UNPIVOT
  (
    Value FOR NUTCODE IN 
        (N1,N2,N3,N4,N5,N6,N7,N8,N9,N10,N11,N12,N13,N14,N15,N16,N17,N18,N19,N20,N21,N22,N23,N24,N25,N26,N27,N28,N29,N30,N31,N32,N33,N34)
  )AS test
) q2
  on q1.Position = right(q1.code, len(q1.code)-1)