根据值从一行创建单独的列

时间:2016-10-07 14:59:21

标签: mysql sql

我有一个名为Source的列,它有2个值“1”和“2”。 我希望将它显示在2列中,例如Source_1,它只显示值“1”,Source_2显示值“2”。 鉴于我的查询,我不知道如何实现它:

    Select 
    b.[path],
    count(*) as "No of Calls",
    count(a.Source) as "Source_1 calls",
    count(a.Source) as "Source_2 calls",
    a.TimeDataRetrieval as "DB Retrieval time",
    a.TimeProcessing as "Processing time",
    a.TimeRendering as "Rendering Time"

    FROM LogStorage a inner join Catalog b on a.[ReportID] = b.[ItemID]

    where b.[path] = ('/../some_path')  and a.[Source]=2
    group by b.[path]

这是我被困的地方。我应该在where子句中做什么,因为我不能有。[Source] = 1和2

感谢。

1 个答案:

答案 0 :(得分:3)

使用Conditional Aggregate

Select 
b.[path],
count(*) as "No of Calls",
count(case when a.Source=1 then 1 end) as "Source_1 calls",
count(case when a.Source=2 then 1 end) as "Source_2 calls",
a.TimeDataRetrieval as "DB Retrieval time",
a.TimeProcessing as "Processing time",
a.TimeRendering as "Rendering Time"
FROM LogStorage a inner join Catalog b on a.[ReportID] = b.[ItemID]

where b.[path] = ('/../some_path')  and a.[Source]=2
group by b.[path]

或只是

sum(a.Source=1) as "Source_1 calls",
sum(a.Source=2) as "Source_2 calls",
相关问题