【问题标题】:Matrix view generated from two selected columns of a table从表格的两个选定列生成的矩阵视图
【发布时间】:2012-11-16 13:29:42
【问题描述】:

假设我有一个包含Project_typeProject_NoOS_Platform 列的表。这里我有有限的Project_types 和有限的OS_Platforms。我想要一个在Project_typeOS_Platform 之间生成矩阵的数据库视图。

 MY_TABLE : 
 Project_Type     Project_No       OS_Platform 
 Drivers          345              Linux
 WebService       453              Windows                    
 Drivers          034              Windows            
 Drivers          953              Solaris
 DesktopApp       840              Windows 
 WebService       882              Solaris   

现在我有 Project_typeOS_Platform 作为选定的列。我想要这两列具有不同行和列名的矩阵视图。

Project_Type     Linux    Windows     Solaris
WebService       null      true         true
Drivers          true      true         true
DesktopApp       null      true         null

谁能告诉我这是否可能。这怎么可能?

【问题讨论】:

  • “有限”是指您知道每个变量的所有可能值吗?如果是这样,这将变得容易。
  • 是的,所有可能的值都是已知的......但我对不参与的值不感兴趣

标签: sql database view pivot


【解决方案1】:

这基本上是一个PIVOT 查询,您可以将数据行转换为列。由于您需要 true/null 值,因此执行此操作的最简单方法是使用聚合函数和 CASE 语句:

select project_type,
  max(case when os_platform ='Linux' then 'true' else null end) Linux,
  max(case when os_platform ='Windows' then 'true' else null end) Windows,
  max(case when os_platform ='Solaris' then 'true' else null end) Solaris
from yourtable
group by project_type

SQL Fiddle with Demo

结果是:

| PROJECT_TYPE |  LINUX | WINDOWS | SOLARIS |
---------------------------------------------
|   DesktopApp | (null) |    true |  (null) |
|      Drivers |   true |    true |    true |
|   WebService | (null) |    true |    true |

【讨论】:

  • @user1860322 很高兴为您提供帮助,如果任何答案对您有帮助,请务必通过左侧的复选标记接受。它可以帮助未来的访问者,并且您会因为接受而获得代表。
【解决方案2】:

如果您使用的 SQL 产品支持专用 PIVOT 功能,您也可以尝试使用它。比如下面的would work in SQL Server 2005+

SELECT *
FROM (
  SELECT DISTINCT
    Project_Type,
    'true' AS flag,
    OS_Platform
  FROM MY_TABLE
) s
PIVOT (
  MAX(flag)
  FOR OS_Platform IN (
    Linux, Windows, Solaris
  )
) p
;

Oracle 数据库是另一个支持 PIVOT 的产品,尽管我不确定它是在哪个版本中首次引入的。在将 PIVOT 的 IN 列表中的每一列括在单引号中后,您就可以运行上述查询 in Oracle,如下所示:

... IN (
  'Linux', 'Windows', 'Solaris'
)
...

【讨论】:

  • 它运行良好并且能够了解新概念 PIVOT。非常感谢。
【解决方案3】:

您需要转置/取消转置您的值以将它们转换为您选择的格式。

这是关于堆栈溢出的谷歌搜索。任何这些都会对你很好。 https://www.google.com/search?q=sql+pivot+unpivot+site%3Astackoverflow.com&oq=sql+pivot+unpivot+site%3Astackoverflow.com&aqs=chrome.0.57.9985&sugexp=chrome,mod=8&sourceid=chrome&ie=UTF-8

现在,您将在此处看到两种类型的答案。第一个是常规的透视/反透视操作。这些对 已知 数据集的工作非常好(容易,但不快)。也就是说,如果您了解所有项目类型和平台,这将很好。

第二种是动态pivot,或者说是使用动态SQL创建的pivot。这比较麻烦,但允许您任意组合字段。

祝你好运!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-09
    • 2014-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多