如何针对不同条件为同一列显示两次结果

时间:2014-03-13 21:02:25

标签: sql-server

我有一张表格如下

Campaign       Status
A             InProgress
B             NotStarted
A             NotStarted             
C             NotStarted
A             NotStarted
B             InProgress
A             NotStarted
C             InProgress

我需要像

这样的结果
Campaign   InProgress   NotStarted
    A        1           2
    B        1           1
    C        1           1

这里我试图计算条件状态并显示为不同的字段 这有可能吗? 我正在尝试以下查询

select Campaign, Count(Case when Statusid=1 then StatusId else 0 end) as NotStarted, Count(Case when Statusid=2 then StatusId else 0 end) as InProgress FROM [TLDCRM2].[dbo].[vPipeline]
group by Campaign

不允许case语句中的不同字段

请帮助显示以上内容 提前谢谢

4 个答案:

答案 0 :(得分:1)

你可以这样做

SELECT Campaign, 
       InProgress = SUM(CASE Status WHEN 'InProgress' THEN 1 ELSE 0 END),
       NotStarted = SUM(CASE Status WHEN 'NotStarted' THEN 1 ELSE 0 END)
  FROM YourTable
 GROUP BY Campaign

或者你应该看看PIVOT。

答案 1 :(得分:1)

您可以使用PIVOT功能来实现此结果。

SELECT *
FROM
(
SELECT
[Campaign] AS Campaign, -- grouping column
[Campaign] AS DupCampaign, -- grouping column
[Status] -- spreading column
FROM vPipeline
) AS Data
PIVOT(
COUNT([DupCampaign]) 
FOR [Status] 
IN ([InProgress], [NotStarted]) 
) AS PIV

我让SQL创建了这个表及其行 -

USE [Stackoverflow]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[vPipeline](
    [Id] [int] NULL,
    [Campaign] [varchar](1) NULL,
    [Status] [varchar](50) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
INSERT [dbo].[vPipeline] ([Id], [Campaign], [Status]) VALUES (1, N'A', N'InProgress')
INSERT [dbo].[vPipeline] ([Id], [Campaign], [Status]) VALUES (2, N'B', N'NotStarted')
INSERT [dbo].[vPipeline] ([Id], [Campaign], [Status]) VALUES (3, N'A', N'NotStarted')
INSERT [dbo].[vPipeline] ([Id], [Campaign], [Status]) VALUES (4, N'C', N'NotStarted')
INSERT [dbo].[vPipeline] ([Id], [Campaign], [Status]) VALUES (5, N'A', N'NotStarted')
INSERT [dbo].[vPipeline] ([Id], [Campaign], [Status]) VALUES (6, N'B', N'InProgress')
INSERT [dbo].[vPipeline] ([Id], [Campaign], [Status]) VALUES (7, N'A', N'NotStarted')
INSERT [dbo].[vPipeline] ([Id], [Campaign], [Status]) VALUES (8, N'C', N'InProgress')

答案 2 :(得分:0)

多个选项:

select Campaign, 
    Count(Case when Statusid=1 then StatusId else NULL end) as NotStarted, 
    Count(Case when Statusid=2 then StatusId else NULL end) as InProgress 
    FROM [TLDCRM2].[dbo].[vPipeline]
group by Campaign

select Campaign, 
    Sum(Case when Statusid=1 then 1 else 0 end) as NotStarted, 
    Sum(Case when Statusid=2 then 1 else 0 end) as InProgress 
    FROM [TLDCRM2].[dbo].[vPipeline]
    group by Campaign

答案 3 :(得分:0)

查询中存在一些语法错误。

试试这个:

select
  Campaign, 
  SUM(Case Status when 'InProgress' then 1 else 0 end) as InProgress, 
  SUM(Case Status when 'NotStarted' then 1 else 0 end) as NotStarted
FROM [vPipeline]
group by Campaign;

SQL小提琴here