sql - 从多个中选择以水平方式检索数据,将一个表的数据作为列

时间:2017-07-26 11:37:57

标签: sql sql-server

  • 我有表T1(idT1,名称)
  • 我有表T2(idT2,OptionDescription)
  • 最后我有表T3(idT3,T1Id,T2Id,Selected)

假设有T1:

idT1    Name
1       John
2       Mary
3       Bill

和T2

idT2    OptionDescription
1       "Available On Monday"
2       "Available On Tuesdey"
3       "Available all Nights"

和T3

idT3    T1Id    T2Id    Selected
1       1       1       True
2       1       2       True
3       1       3       False
4       2       1       False
5       2       2       False
6       2       3       True

是否可以在"水平"中编写一个检索T1和T2 / T3数据的查询。方式(我的意思是T2作为列结果的描述)如:

idT1    Name    "Available On Monday"   "Available On Tuesdey"  "Available all Nights"
1       John    True                    True                    False
2       Mary    False                   False                   True

3 个答案:

答案 0 :(得分:0)

使用Pivot

>>> input_dataframe.join(delta_dataframe,['custid','sourceid'],'outer').select('custid','sourceid',F.coalesce(delta_dataframe['value'],input_dataframe['value']).alias('value')).show()
+------+--------+-------------+
|custid|sourceid|        value|
+------+--------+-------------+
|    10|      15|   new_value2|
|    10|      11|updated_value|
|    10|      12|  test_value2|
+------+--------+-------------+

答案 1 :(得分:0)

DECLARE @T1 TABLE (idT1 INT,   Name VARCHAR(50))
INSERT INTO @T1 VALUES
(1, 'John'),
(2, 'Mary'),
(3, 'Bill');
DECLARE @T2 TABLE (idT2 INT,  OptionDescription VARCHAR(50))
INSERT INTO @T2 VALUES
(1, 'Available On Monday'),
(2, 'Available On Tuesdey'),
(3, 'Available all Nights');
DECLARE @T3 TABLE (idT3 INT,   T1Id INT, T2Id INT, Selected VARCHAR(50))
INSERT INTO @T3 VALUES
(1, 1, 1, 'True'),
(2, 1, 2, 'True'),
(3, 1, 3, 'False'),
(4, 2, 1, 'False'),
(5, 2, 2, 'False'),
(6, 2, 3, 'True');

-- THE QUERY USING CTE -- NOTE YOU MUST NOT USE CTE
; WITH CTE AS 
(
SELECT 
T1.idT1,
T1.Name,
T2.OptionDescription,
T3.Selected
FROM @T3 AS T3
INNER JOIN @T1 AS T1 ON T3.T1Id=T1.idT1
INNER JOIN @T2 AS T2 ON T3.T2Id=T2.idT2

)
SELECT * FROM CTE
PIVOT
(
MAX(selected) FOR OptionDescription IN ([Available On Monday],[Available On Tuesdey],[Available all Nights])
) AS PV1

答案 2 :(得分:0)

选择* 从 (  选择x.IdT1,x.Name,t2.OptionDescription,x.selected from  (选择t1.IdT1,t1.Name,t3.T2Id,t3。从t1加入t3选择   t1.idT1 = t3.T1Id)X   在x.T2Id = t2.IdT2上加入T2 )src 枢 (   最大值(选择)的   for OptionDescription in([可在星期一],[可在Tuesdey上使用],[可用所有夜晚]) 枢纽;