我正在使用具有表x
的SQL Server数据库。
表:x
x_id Type Text ID
-------------------------------------------
| 1 | Type1 | txt1 | id1
| 2 | Type2 | txt2 | id2
| 3 | Type3 | txt3 | id1
| 4 | Type3 | txt4 | id3
这里,每个ID可以有Type1,Type2,Type3等不同的文本。
我需要生成包含字段ID,Type1_exists,Type2_exists,Type3_exists,Type1_Text,Type2_Text,Type3_Text的报告,其中存在列应该说明ID是否具有该文本(Y / N)。如果ID的记录类型为" Type1"然后Type1_exists值应为" Y"否则" N"。
所以,我期待的样本结果是
ID Type1_Exists Type1_Text Type2_Exists Type2_Text Type3_Exists Type3_Text
---------------------------------------------------------------------
| id1 | Y | txt1 | N | | Y | txt3
| id2 | N | | Y | txt2 | N |
| id3 | N | | N | | Y | txt4
答案 0 :(得分:2)
您可以使用PIVOT或条件聚合
PIVOT:
SELECT
[ID],
[Type1_Exists] = CASE WHEN [Type1] IS NULL THEN 'N' ELSE 'Y' END,
[Type1_Text] = [Type1],
[Type2_Exists] = CASE WHEN [Type2] IS NULL THEN 'N' ELSE 'Y' END,
[Type2_Text] = [Type2],
[Type3_Exists] = CASE WHEN [Type3] IS NULL THEN 'N' ELSE 'Y' END,
[Type3_Text] = [Type3]
FROM (
SELECT [ID], [Type], [Text]
FROM x
) t
PIVOT (
MAX([Text])
FOR [Type] IN ([Type1],[Type2],[Type3])
) p
有条件的聚合:
SELECT
[ID],
MAX(CASE WHEN [Type] = 'Type1' THEN 'Y' ELSE 'N' END) AS [Type1_Exists],
MAX(CASE WHEN [Type] = 'Type1' THEN [Text] END) AS [Type1_Text],
MAX(CASE WHEN [Type] = 'Type2' THEN 'Y' ELSE 'N' END) AS [Type2_Exists],
MAX(CASE WHEN [Type] = 'Type2' THEN [Text] END) AS [Type2_Text],
MAX(CASE WHEN [Type] = 'Type3' THEN 'Y' ELSE 'N' END) AS [Type3_Exists],
MAX(CASE WHEN [Type] = 'Type3' THEN [Text] END) AS [Type3_Text]
FROM
x
GROUP BY [ID]
答案 1 :(得分:0)
一种方法是将表连接到自身,在ON子句中有限制为每种类型提取行,如下所示:
select distinct x0.ID,
case when x1.Text is null then 'N' else 'Y' end type1_exists,
x1.Text type1_text,
case when x2.Text is null then 'N' else 'Y' end type2_exists,
x2.Text type2_text,
case when x3.Text is null then 'N' else 'Y' end type3_exists,
x3.Text type3_text,
case when x4.Text is null then 'N' else 'Y' end type4_exists,
x4.Text type4_text
from x x0 left join x x1 on x0.ID = x1.ID and x1.Type = 'Type1'
left join x x2 on x0.ID = x2.ID and x2.Type = 'Type2'
left join x x3 on x0.ID = x3.ID and x3.Type = 'Type3'
left join x x4 on x0.ID = x4.ID and x4.Type = 'Type4'
order by 1;
SQL Server也明确支持使用PIVOT的交叉表查询。