我在 SQL Server 中有 2 个表,一个
ItemTable
和一个 PropertyTable
。
它们的定义如下:
ItemTable
:
商品名称 | 项目已启用 | 对象名称 |
---|---|---|
规则01 | 1 | 对象01 |
规则02 | 1 | 对象01 |
规则03 | 1 | 对象03 |
PropertyTable
:
属性名称 | 属性已启用 | 对象名称 |
---|---|---|
提案01 | 1 | 对象01 |
提案02 | 1 | 对象02 |
ItemTable
中可能存在 ObjectName
中不存在的行,反之亦然。我编写了一个存储过程,它根据传入的 PropertyTable
返回一个透视结果集。例如,使用“Object01”作为参数传入,存储过程应返回如下内容:
规则01 | 规则02 | 提案01 | |
---|---|---|---|
1 | 1 | 1 |
ObjectName
和
Object02
的行。如何获取传入参数的旋转列。我认为我的代码中缺少一个 where 子句。
存储过程代码:
Object03
项目已启用 | 对象名称 | |
---|---|---|
1 | 对象01 | |
1 | 对象01 | |
1 | 对象03 | |
1 | 对象05 |
属性已启用 | 对象名称 | |
---|---|---|
1 | 对象01 | |
1 | 对象02 | |
1 | 对象04 |
DECLARE @cols AS NVARCHAR(MAX) = '';
DECLARE @cols1 AS NVARCHAR(MAX) = '';
DECLARE @query AS NVARCHAR(MAX) = '';
SELECT @cols = @cols + QUOTENAME(ItemName) + ','
FROM
(SELECT DISTINCT ItemName
FROM ItemTable
WHERE LOWER(ObjectName) = LOWER('Object01')
GROUP BY ItemName) AS tmp
SELECT @cols = SUBSTRING(@cols, 0, LEN(@cols))
SELECT @cols1 = @cols1 + QUOTENAME(PropertyName) + ','
FROM
(SELECT DISTINCT PropertyName
FROM PropertyTable
WHERE LOWER(ObjectName) = LOWER('Object01')
GROUP BY PropertyName) AS tmp1
SELECT @cols1 = SUBSTRING(@cols1, 0, LEN(@cols1))
SET @query = '
SELECT * FROM
(
SELECT
I.ItemName AS [Name]
,V.ValueColumn
,I.ObjectName AS [ObjectName]
FROM ItemTable I
--tried adding a where clause here; isn't working
CROSS APPLY (
SELECT
CAST(I.IsEnabled AS VARCHAR(50)) AS [ValueColumn]
) V
UNION
SELECT
P.PropertyName as [Name]
,V1.ValueColumn
,P.ObjectName AS [ObjectName]
FROM PropertyItem P
--tried adding a where clause here; isn't working
CROSS APPLY (
SELECT
P.PropertyIsEnabled AS [ValueColumn]
) V1
) src
PIVOT
(
max(ValueColumn) for [Name] in (' + @cols + ', ' + @cols1 + ')
) piv'
提案01 | 规则01 | 规则02 | |
---|---|---|---|
1 | 1 | 1 |