【问题标题】:Distinct value with same date in SQLSQL中具有相同日期的不同值
【发布时间】:2021-05-04 01:49:21
【问题描述】:

我有这样的表:

id    account_no  tax    date
1         201      10    2021-01-31
2         201      0     2021-01-31
3         301      20    2021-01-31
4         401      20    2020-10-10

我想要 account_no 的不同值,同时具有 tax <> 0date = '2021-01-31'

预期结果:

account_no
201
301

我应该如何查询? 我正在使用 Visual Studio 13。

我正在查询:

Select distinct Account_No from ( 
Select Account_No, date, count(*) jumlah from table
Where date = '2021-01-31' and tax <> 0
Group By Account_No, date
Having count(*) > 1
) a

但结果一直显示不同的 account_no 和重复的日期

【问题讨论】:

  • 到目前为止,您尝试做什么?你能分享一些你的努力吗?
  • 顺便说一句,我猜到Visual Studio会与mssql server结合使用
  • @FranciscodeCastro 即时编辑查询
  • @hifanaya,查询真的很简单,就像你描述的那样。已经有一个有效的答案

标签: mysql sql group-by distinct


【解决方案1】:

这很简单(甚至查询的语法与您给出的描述非常相似..):

select distinct account_no from myTable
where tax <> 0 and date = '2021-01-31';

【讨论】:

    【解决方案2】:

    让我先解释一下为什么您的查询不能按预期工作及其分析

    Select distinct Account_No from ( 
        Select Account_No, date, count(*) jumlah from table
        Where date = '2021-01-31' and tax <> 0
        Group By Account_No, date
        Having count(*) > 1) a
    
    • 您正在使用 count(*)>1,这将丢弃单次出现的行
    • 分析:
    1. 您将首先选择日期 = '2021-01-31' 和税费 0
    2. 的所有记录
    3. 您将根据帐号和日期对这些记录进行分组 => 并查找计数。 此计数不会为您提供结果所需的任何信息。您只需要帐户

    @Michał Turczyn 建议的最佳查询

    select distinct account_no from myTable
    where tax <> 0 and date = '2021-01-31';
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-06
      • 2017-04-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多