如何加快从另一列中的值创建新列的查询?

时间:2016-11-21 14:11:17

标签: sql-server

我不确定我要求的措辞,但我正在尝试为报告创建查询,我想要创建的每个列的所有值都在一列中,目前。这是我目前的查询:

SELECT [SubjectID]
    ,(SELECT [DataValue] 
      FROM [SummarySubjectDataValueAll]
      WHERE [LibraryEventID] IN (
                SELECT [LibraryEventID] 
                FROM [LibraryEvent] 
                WHERE [Name] LIKE '%First Name%')
     ) as FirstName
    ,(SELECT [DataValue] 
      FROM [SummarySubjectDataValueAll]
      WHERE [LibraryEventID] IN 
                     (SELECT [LibraryEventID] 
                      FROM [LibraryEvent] 
                       WHERE [Name] LIKE '%Last Name%')) as LastName
    ,(SELECT [DataValue] 
      FROM [SummarySubjectDataValueAll]
      WHERE [LibraryEventID] IN (
               SELECT [LibraryEventID] 
               FROM [LibraryEvent] 
               WHERE [Name] LIKE 'Primary Phone')) as Phone
    ,(SELECT [DataValue] 
      FROM [SummarySubjectDataValueAll]
      WHERE [LibraryEventID] IN (
             SELECT [LibraryEventID] 
             FROM LibraryEvent] 
             WHERE [Name] = 'Secondary Phone')) as Phone2
      ,(SELECT [DataValue] 
        FROM [SummarySubjectDataValueAll]
        WHERE [LibraryEventID] IN (
               SELECT [LibraryEventID] 
               FROM [LibraryEvent] 
               WHERE [Name] = 'Next of Kin Phone')) as KinPhone
  FROM [SummarySubjectDataValueAll]
  WHERE DataValue = @Phone

(就个人而言,他们会快速查询我需要的东西)。尝试提取信息时,它运行时间超过10分钟或更长时间,我知道这是因为我让它再次运行相同的表6次。我没有想到如何以更有效的方式做到这一点。有人可以帮忙吗?关于这份报告正在做什么的一些背景:它本质上是一个反向电话目录。我需要根据他们的电话号码提取个人信息,这可能是上述3种类型中的任何一种(小学,中学或近亲)。

提前谢谢

1 个答案:

答案 0 :(得分:2)

您可以通过使用CASE EXPRESSION的条件聚合来简单地避免所有这些嵌套选择:

SELECT t.subjectID,
       MAX(CASE WHEN t.name LIKE '%First Name%' THEN t.DataValue END) as FirstName,
       MAX(CASE WHEN t.name LIKE '%Last Name%' THEN t.DataValue END) as LastName,
       MAX(CASE WHEN t.name = 'Primary Phone' THEN t.DataValue END) as Phone,
       MAX(CASE WHEN t.name = 'Secondary Phone' THEN t.DataValue END) as Phone2,
       MAX(CASE WHEN t.name = 'Next of Kin Phone' THEN t.DataValue END) as KinPhone
FROM SummarySubjectDataValueAll t
JOIN LibraryEvent s
 ON(t.LibraryEventID = s.LibraryEventID)
GROUP BY t.subjectID