简体   繁体   English

如何在我的 PIVOT 值中为我的每个列添加一个额外的非聚合列?

[英]How do I include an additional non-aggregated column for each of my in my PIVOT values?

I have the following code fragment which gives me the current results below.我有以下代码片段,它给了我下面的当前结果 I'm attempting to add an additional column for each of my pivoted values in order to include the lastview data for each of my siteuserid / tagname combo (see expected results ).我正在尝试为每个透视值添加一个附加列,以便包含我的每个 siteuserid / tagname 组合的lastview数据(请参阅预期结果)。 Since this column isn't an aggregation, I don't believe an additional pivot would help.由于本专栏不是汇总,我不相信额外的 pivot 会有所帮助。 I've tried multiple ways of adding lastview , but it always results in additional rows rather than the desired output.我尝试了多种添加lastview的方法,但它总是导致额外的行而不是所需的 output。

create table #taghits (userid int, email varchar(20), tagname varchar(20), hits int, lastview date)

insert into #taghits select 1, 'email1@here.com', 'tag1', 3, '2020-03-24';
insert into #taghits select 2, 'email2@here.com', 'tag1', 1, '2020-03-17';
insert into #taghits select 2, 'email2@here.com', 'tag2', 1, '2020-03-18';
insert into #taghits select 3, 'email3@here.com', 'tag1', 2, '2020-03-25';
insert into #taghits select 3, 'email3@here.com', 'tag2', 5, '2020-03-28';

select * from #taghits;

DECLARE @Columns3 as NVARCHAR(MAX)
SELECT @Columns3 = ISNULL(@Columns3 + ', ','') + QUOTENAME(TagName)
FROM (
    select distinct TagName
    from #taghits
) AS TagNames
ORDER BY TagNames.TagName

DECLARE @scolumns as NVARCHAR(MAX)
SELECT @scolumns = ISNULL(@Scolumns + ', ','')+ 'ISNULL(' + QUOTENAME(TagName) + ', 0) AS '+ QUOTENAME(TagName)
FROM (select distinct TagName
    from #taghits) AS TagNames
ORDER BY TagNames.TagName

DECLARE @SQL as NVARCHAR(MAX)
SET @SQL = '
    select userid, email, ' + @scolumns + '
    from
        (
        select userid, email, tagname, hits
        from #taghits
        ) as TagHits
    PIVOT (
        SUM(hits)
        FOR TagName IN (' + @Columns3 + ')
    ) AS PivotTable
    order by userId
'

exec sp_executesql @SQL;

Current Result当前结果

| userid | email           | tag1 | tag2 |
|--------|-----------------|------|------|
| 1      | email1@here.com | 3    | 0    |
| 2      | email2@here.com | 1    | 1    |
| 3      | email3@here.com | 2    | 5    |

Desired Result期望的结果

| userid | email           | tag1_hits | tag1_lastview | tag2_hits | tag2_lastview |
|--------|-----------------|-----------|---------------|-----------|---------------|
| 1      | email1@here.com | 3         | 2020-03-24    | 0         | null          |
| 2      | email2@here.com | 1         | 2020-03-17    | 1         | 2020-03-18    |
| 3      | email3@here.com | 2         | 2020-03-25    | 5         | 2020-03-28    |

try the following:尝试以下操作:

DECLARE @cols AS NVARCHAR(MAX),
        @query  AS NVARCHAR(MAX);

SET @cols = STUFF((select distinct ', 
            SUM(CASE WHEN tagname=''' + CAST(tagname as varchar(10)) + ''' THEN [hits] ELSE 0 END) AS [' + CAST(tagname as varchar(10)) + '_hits],
            MAX(CASE WHEN tagname=''' + CAST(tagname as varchar(10)) + ''' THEN [lastview] ELSE NULL END) AS [' + CAST(tagname as varchar(10)) + '_lastview]'
            /*---------------You can add other columns here similar to above--------------*/
            FROM #taghits 
            FOR XML PATH(''),type).value('.','varchar(max)'),1,2,'')
SET @query = 'SELECT userid, email, ' + @Cols + '  FROM #taghits group by userid, email' 

print (@query)
exec(@query)

Please see db<>fiddle here .在此处查看 db<>fiddle。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 BigQuery : GROUP BY 包含非聚合列 - BigQuery : GROUP BY include the non-aggregated column 如何基于另一个列值在非聚合的SQL查询中返回最大值 - How do I return max value in a non-aggregated sql query based on another column value 如何使用聚合列获取非聚合列的值? - How can I get the value of non-aggregated column with an aggregated column? 是否可以在SQL的聚合函数中包含未聚合的列,而不将其放入GROUP BY子句中? - Can I include a non-aggregated Column in an aggregate function in SQL without putting it into a GROUP BY clause? 使用MySQL GROUP BY,如何控制在非聚合列中选择的默认值? - With a MySQL GROUP BY, how do I control the default value to choose in non-aggregated columns? 当在Oracle中应用group by子句时,如何获取不同的非聚合列以及聚合列? - how to get distinct non-aggregated columns along with aggregated column when group by clause is applied in oracle? 在MySQL中通过statment选择相应的非聚合列 - Select corresponding non-aggregated column after group by statment in MySQL 如何旋转我的表格并用逗号分隔“聚合”字段? - How can I Pivot my Table and separate 'aggregated' fields with a Comma? 如何为逻辑聚合数据并在输出中显示非聚合结果? - How to aggregate data for logic and show non-aggregated results in the output? 如何在聚合和非聚合数据集上获得相同的 AVG() 值 - How to get the same value of AVG() on both aggregated & non-aggregated dataset
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM