【问题标题】:Get multiple columns for different WHERE clause on the same column in SQL获取SQL中同一列上不同WHERE子句的多列
【发布时间】:2020-06-13 09:25:29
【问题描述】:

我有一个包含date 的表和列(比如字符串)。我需要从同一日期列中获取两列,例如 countin(2020)countin(2019),这样日期就像“2020%”或“2019%”,我希望它们作为单独的列。

我的查询是这样的。

select C.pin_code, count(distinct(C.customer_code)) as 2020 
from table 
group by C.pin_code

我的输出是这样的

对我来说,除了 2020 年之外,应该还有一个名为 2019 的列,它在 2019 年提供与 2020 年相同的数据。

如果我强调了什么,请在 cmets 中告诉我。

【问题讨论】:

  • (1) 用您正在使用的数据库标记您的问题。 (2) 你的数据是什么样的? (3) 您现有的查询与 2020 年有什么关系?

标签: sql where-clause calculated-columns having


【解决方案1】:
Select
Count(Year(year_col)) as year,
Pin_code
From T
Group_by pin_code
Order by pin_code desc;

如果您需要年份列中的这些值,您可以使用数据透视

【讨论】:

    【解决方案2】:

    对我来说,除了 2020 年之外,应该还有一个名为 2019 的列,它在 2019 年提供与 2020 年相同的数据。

    如果您的数据中包含日期,那么我希望得到这样的查询:

    select C.pin_code,
           count(distinct case when year(C.date) = 2020 then C.customer_code end) as cnt_2020, 
           count(distinct case when year(C.date) = 2019 then C.customer_code end) as cnt_2019
    from C 
    group by C.pin_code;
    

    众所周知,日期/时间函数依赖于数据库。但是year() 很常见,所有数据库都以某种方式具有此功能。

    【讨论】:

    • 您好,我收到错误“在数据库 'Salestable' 上执行 SQL 查询时出错:没有这样的功能:年份”我正在使用 sqlite
    猜你喜欢
    • 2014-02-16
    • 2012-04-11
    • 2011-05-21
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-01
    相关资源
    最近更新 更多