是否可以按表中的元素进行分组(如中所示COLUMN LIKE='Value%'
)PIVOT
?我有一个表[DBT]。[Status],其中包含各种状态(数据库,实例等),并且不想将所有PROD和TEST值作为单个值进行透视/查询,而是将它们分组。
例如代替具有用于状态列Prod
,Prod ACC
,Prod APP
,...等。我将仅有一个包含的值列Name LIKE 'Prod%'
和Name LIKE 'Test%'
。
到目前为止,我有:
表定义
CREATE TABLE [DBT].[Status](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](50) NOT NULL,
CONSTRAINT [PK_Status] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY],
CONSTRAINT [IX_Status] UNIQUE NONCLUSTERED
(
[Name] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY]
) ON [PRIMARY]
GO
表值
INSERT INTO [DBT].[Status]
(
-- ID -- this column value is auto-generated
Name
)
VALUES
('Test ACC'),
('Test APP'),
('Test DBA'),
('Prod ACC'),
('Prod APP'),
('Prod DBA'),
('Prod'),
('Test'),
('Migrated'),
('Offline'),
('Reserved')
透视状态表
SELECT 'Database Status' AS [DB Status],
[1] AS [Test ACC], [2] AS [Test APP], [3] AS [Test DBA], [4] AS [Prod ACC], [5] AS [Prod APP], [6] AS [Prod DBA], [7] AS [Prod], [8] AS [Test], [9] AS [Migrated], [10] AS [Offline], [11] AS [Reserved]
FROM
(
SELECT ID, Name FROM [DBT].[Status]
) AS Source
PIVOT
(
COUNT(Name) FOR ID IN ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11])
) AS PivotTable
到目前为止的输出
DB Status Test ACC Test APP Test DBA Prod ACC Prod APP Prod DBA Prod Test Migrated Offline Reserved
--------------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- -----------
Database Status 1 1 1 1 1 1 1 1 1 1 1
db <>小提琴
到目前为止的dbfiddle。
题
我不希望将多个Test...
和Prod....
值包含多个行,而是将它们分组,类似于以下内容:
DB Status | Test | Prod | Migrated | Offline | Reserved
--------------- | ---- | ---- | -------- | ------- | --------
Database Status | 4 | 4 | 1 | 1 | 1
我不知道如何解决我的问题。(老实说,我只是经过反复试验和错误才昨天才掌握PIVOT)。
这个问题与如何在我已经问过的多个表上创建分组项目的总和/计数松散相关。表[DBT]。[Instance]和[DBT]。[Database]包含具有[StatusID]的列,该列与我们现在正在查看的表相对应。