【问题标题】:In SQL how can i show the sales of city's with 0 when they dont have sales in a year. I have city table and transaction table在 SQL 中,当城市在一年内没有销售时,我如何显示城市的销售量。我有城市表和交易表
【发布时间】:2021-04-20 16:18:26
【问题描述】:

我有一个表格,其中包含每个城市每年的总销售额,但我的表格没有某些年份的城市销售额,我们也看不到该信息。

现在我想准备一个结果集,表示所有城市的当年销售额,并以值为 0 的方式显示一年内没有销售额的城市

城市表

CityKey City
1 NYC
2 Dallas
3 San Francisco

事务表

City Total sales Year
NYC 100 2019
Dallas 50 2019
San Francisco 100 2019
NYC 222 2020

输出 - 每个城市的交易:

City Total sales Year
NYC 100 2019
Dallas 50 2019
San Francisco 100 2019
NYC 222 2020
Dallas 0 2020
San Francisco 0 2020

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:

    使用cross join 生成所有行,然后left join 引入现有数据:

    select c.city, y.year, coalesce(t.total_sales, 0)
    from cities c cross join
         (select distinct year from transactions) y left join
         transactions t
         on t.city = c.city and t.year = y.year;
    

    【讨论】:

    • 这段代码没有帮助,还有很多性能问题。我分别有 City 表、Year 表和 transaction 表
    • @user15488631 。 . .然后只需使用年份表而不是y。你没有在你的问题中提到它。
    猜你喜欢
    • 2016-10-12
    • 2015-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-04
    • 1970-01-01
    • 2022-08-10
    相关资源
    最近更新 更多