SQL Pivot Table w/ and w/o Distinct Same Result

Posted

技术标签:

【中文标题】SQL Pivot Table w/ and w/o Distinct Same Result【英文标题】: 【发布时间】:2020-02-24 11:56:23 【问题描述】:

我正在尝试使用数据透视表按位置获取客户访问计数的结果,但 count(distinct customer_id) 和 count(customer_id) 返回相同的结果。我该怎么办?我应该只为那部分编写另一个子查询吗?

select Locationname as 'Location',[2020],[2019],[2018],[2017],[2016],[2015],[2014],[2013],[2012],[2011],[2010]
from (select year(date_when) [date_when2],Locationname ,count(distinct customer_id) [cst_id] from record
group by date_when,Locationname) as aws

PIVOT(
    count([cst_id]) 
    FOR [date_when2] IN (
        [2020],
        [2019],
        [2018],
        [2017],
        [2016],
        [2015],
        [2014],
        [2013],
        [2012],
        [2011],
        [2010]  
        )
) AS pivot_table

按要求编辑: 这是查询的当前结果,但是我想查看唯一客户数,并且 distinct 没有区别。

【问题讨论】:

请提供样本数据和期望的结果。 【参考方案1】:

我推荐条件聚合:

select Locationname as'Location,
       count(distinct case when year(date_when) = 2020 then customer_id end) as custs_2020,
       count(distinct case when year(date_when) = 2019 then customer_id end) as custs_2019,
       count(distinct case when year(date_when) = 2018 then customer_id end) as custs_2018,
       count(distinct case when year(date_when) = 2017 then customer_id end) as custs_2017,
       count(distinct case when year(date_when) = 2016 then customer_id end) as custs_2016,
       count(distinct case when year(date_when) = 2019 then customer_id end) as custs_2015,
       count(distinct case when year(date_when) = 2015 then customer_id end) as custs_2014,
       count(distinct case when year(date_when) = 2014 then customer_id) as custs_2013,
       count(distinct case when year(date_when) = 2013 then customer_id end) as custs_2012,
       count(distinct case when year(date_when) = 2012 then customer_id end) as custs_2011,
       count(distinct case when year(date_when) = 2011 then customer_id end) as custs_2010
from record
group by Locationname;

我不喜欢pivot 语法。它很挑剔、不标准、难以理解(“子查询”必须恰到好处才能与外部查询一起使用),而且不是很通用。

【讨论】:

此处相同,但对于我未来的查询,我需要全面学习数据透视表,因此我需要了解为什么 distinct 无法正常工作。非常感谢你的这个查询,但我需要用数据透视表来做:( 交叉表是一种透视形式,@Anil。然而,好处是它可以转移到其他 RDBMS 并且更灵活

以上是关于SQL Pivot Table w/ and w/o Distinct Same Result的主要内容,如果未能解决你的问题,请参考以下文章

SQL Server Rank() Over Partition w/Back and Forth 值

使用 PIVOT 函数的行到列 (Oracle)

table JS合并单元格

T-SQL Recipes之Dynamic PIVOT and UNPIVOT

PL-SQL:ORA-00904 - 标识符无效 - Select and Pivot 子句中的列

MS SQL PIVOT MONTH, QUARTER AND YEAR - 如果存在类似月份值,则显示错误数据的季度