从一行中的不同行中选择值

时间:2017-06-14 13:06:08

标签: sql sql-server tsql

我有两张桌子:

CREATE TABLE MAIN (
    [ID] INT PRIMARY KEY,
    [TIMESTAMP] DATETIME,
    [NAME] VARCHAR(15)
    );

CREATE TABLE SEC (
    [ID] INT PRIMARY KEY,
    [TIMESTAMP] DATETIME,
    [VAL] INT,
    [TYPE] VARCHAR(10)
    );

我想从两个表中选择值。第二个表中的数据在type列中具有不同的值,但与main表数据具有相同的时间戳。

SELECT M.[TIMESTAMP], [NAME], [VAL] AS 'VAL_TYPE_1', [VAL] AS 'VAL_TYPE_2'
FROM MAIN M
LEFT JOIN SEC S ON M.TIMESTAMP = S.TIMESTAMP
WHERE S.TYPE = 'TYPE_1' OR S.TYPE = 'TYPE_2';

对于来自main表的所有时间戳,我想得到TYPE_1的名称和值(如果它不存在则为NULL)和TYPE_2的值(如果是{NULL)则为NULL不存在)。我应该改变什么?

4 个答案:

答案 0 :(得分:1)

这通常是通过CASE

完成的

例如:

SELECT M.[TIMESTAMP], M.[NAME], 
MAX(CASE WHEN S.TYPE = 'TYPE_1' THEN S.[VAL] END) AS [VAL_TYPE_1],  
MAX(CASE WHEN S.TYPE = 'TYPE_2' THEN S.[VAL] END) AS [VAL_TYPE_2] 
FROM MAIN M
LEFT JOIN SEC S ON M.TIMESTAMP = S.TIMESTAMP
WHERE S.TYPE IN('TYPE_1','TYPE_2')
GROUP BY M.[TIMESTAMP], M.[NAME];

如果你想在TIMESTAMP和NAME上分组,那也是可能的

{{1}}

答案 1 :(得分:0)

如果我感觉不对,你需要这样的东西:

SELECT M.[TIMESTAMP]
      ,M.[NAME]
      ,S1.[VAL] AS 'VAL_TYPE_1'
      ,S2.[VAL] AS 'VAL_TYPE_2'
FROM MAIN M
LEFT JOIN SEC S1 ON M.TIMESTAMP = S1.TIMESTAMP
AND S1.TYPE = 'TYPE_1' 
LEFT JOIN SEC S2 ON M.TIMESTAMP = S2.TIMESTAMP
AND S2.TYPE = 'TYPE_2';

答案 2 :(得分:0)

我认为你可以通过简单的联合查询得到这个。希望这有帮助

SELECT M.[TIMESTAMP], [NAME], [VAL] AS 'VAL_TYPE_1', NULL 'VAL_TYPE_2'
FROM MAIN M
LEFT JOIN SEC S ON M.TIMESTAMP = S.TIMESTAMP
WHERE S.TYPE = 'TYPE_1' 

UNION ALL 

SELECT M.[TIMESTAMP], [NAME], NULL 'VAL_TYPE_1' , [VAL] AS 'VAL_TYPE_2'
FROM MAIN M
LEFT JOIN SEC S ON M.TIMESTAMP = S.TIMESTAMP
WHERE S.TYPE = 'TYPE_2' 

答案 3 :(得分:0)

我想你需要这样的东西:

SELECT          M.[TIMESTAMP],
                [NAME],
                T1.[VAL] AS 'VAL_TYPE_1',
                T2.[VAL] AS 'VAL_TYPE_2'
FROM            MAIN M
LEFT OUTER JOIN SEC T1
             ON M.TIMESTAMP = T1.TIMESTAMP
            AND T1.TYPE = 'TYPE_1'
LEFT OUTER JOIN SEC T2
             ON M.TIMESTAMP = T2.TIMESTAMP
            AND T2.TYPE = 'TYPE_2';