简体   繁体   English

如何在SQL中透视表

[英]How to pivot table in SQL

Lab Test Name    Source Collected Date    Results
Urea             6/4/2013 12:00:00 AM           5
Uric Acid        6/4/2013 12:00:00 AM          10
Cholesterol      6/3/2013 12:00:00 AM          25

I have a datatable with above values. 我有一个具有上述值的数据表。
I need to pivot it to following structure: 我需要将其枢转到以下结构:

                      Urea  Uric Acid   Cholesterol
6/4/2013 12:00:00 AM     5         10             -
6/3/2013 12:00:00 AM     -          -            25

If you look at the answer linked by Mikael, you'll realize that you will need to build the columns for your pivot statement dynamically since the PIVOT syntax doesn't allow a subselect within the FOR clause. 如果您查看由Mikael链接的答案,您会意识到,由于PIVOT语法不允许在FOR子句中进行子选择,因此需要动态地为数据透视表语句构建列。 So essentially you need to do something like this: 因此,基本上,您需要执行以下操作:

DECLARE
@cols AS NVARCHAR(MAX),
@y    AS INT,
@sql  AS NVARCHAR(MAX);

-- Construct the column list for the IN clause
-- e.g., [Urea],[Uric Acid],[Cholesterol]
SET @cols = STUFF(
(SELECT N',' + QUOTENAME(y) AS [text()]
FROM (SELECT DISTINCT (LabTestName) AS y FROM YourTable) AS Y
ORDER BY y
FOR XML PATH('')),
1, 1, N'');

You can now build your PIVOT statement as so: 现在,您可以按以下方式构建PIVOT语句:

set @SQL = N'

SELECT   SourceCollectedDate,'+@cols+N' 
FROM    YourTable
PIVOT (
SUM(results) FOR LabTestName IN ( '+@cols+N')
) AS PivotTable
ORDER BY SourceCollectedDate desc
'

And execute it: 并执行它:

EXEC sp_executesql @sql

Which will produce: 会产生:

SourceCollectedDate     Urea    Uric Acid   Cholesterol
2013-06-04 00:00:00.000 5       10          NULL
2013-06-03 00:00:00.000 NULL    NULL        25

Just note that my example has YourTable as the table name. 请注意,我的示例将YourTable作为表名。 You need to replace that with your actual table name. 您需要用实际的表名替换它。

SQL Fiddle (Based off of what Chad created) SQL Fiddle (基于乍得创建的内容)

Here's a solution that doesn't require pivot or dynamic SQL. 这是不需要pivot或动态SQL的解决方案。 The tradeoff is that you need to specify each possible Lab Test Name in your query. 折衷方案是您需要在查询中指定每个可能的实验室测试名称。

SELECT [Source Collected Date],
  MAX(CASE WHEN [Lab Test Name] = 'Urea'
      THEN Results ELSE NULL END) AS Urea,
  MAX(CASE WHEN [Lab Test Name] = 'Uric Acid'
      THEN Results ELSE NULL END) AS [Uric Acid],
  MAX(CASE WHEN [Lab Test Name] = 'Cholesterol'
      THEN Results ELSE NULL END) AS Cholesterol
FROM Table1
GROUP BY [Source Collected Date]

See it working here . 看到它在这里工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM