【问题标题】:Selecting distinct rows based on column根据列选择不同的行
【发布时间】:2014-03-11 15:58:19
【问题描述】:

以这种方式对我的结果数据进行特定查询。

 Id    Size  
 123     1
 123     1
 123     2
 123     2
 134     1
 134     1
 134     2

我希望结果让我计算消除重复大小的次数,例如

 Id    Size  
 123     1
 123     2
 134     1
 134     2

以上是连接两个表的结果。问题是在这种情况下我不能使用 distinct。

表格是这样的

Table1:
   Id Created ... .. .. ..
   123 date1 ....
   134 date2 ....

Table2:     
 Id    Size  
 123     1
 123     2
 134     1
 134     2

我的查询是根据 CreatedDate 从 Table1 中选择的,就像这样

 select count(*)
 from table1

 join table2
 on table1.id = table2.id

 where table1.creates between '' and ''.

如何获得不同的尺寸。

如果我使用 select count(distinct table2.size),它只会为所有行返回 1 和 2。

【问题讨论】:

    标签: sql


    【解决方案1】:
    SELECT DISTINCT Id, Size
        FROM table1
    

    这应该会给你一个不同的 Id 和 Size 组合的列表。

    【讨论】:

    • 是的,它应该可以工作。更准确地说,SELECT DISTINCT ID, Size FROM table1, table2 WHERE table1.Id = table2.Id AND table1.creates between '' and ''
    【解决方案2】:
     select count(distinct table1.id, table2.size)
     from table1
    
     join table2
     on table1.id = table2.id
    
     where table1.creates between '' and ''
    

    有时解决方案是如此明显...... :)

    更新:另一种方式

    select count(*) from (
         select distinct table1.id, table2.size
         from table1
    
         join table2
         on table1.id = table2.id
    
         where table1.creates between '' and ''
    ) sq
    

    【讨论】:

    • count 将导致它只显示计数,而不是行本身。
    • 感谢您的回复。我没有看到上面提到的 count() 有效。 ',' 附近的语法不正确。我应该使用不同的语法吗?
    • @Pheonixblade9 好吧,在问题中它询问的是计数,而不是行数。
    • @user3285499 您使用的是哪个 RDBMS?我的解决方案适用于 MySQL,如 sqlfiddle 所示。我已经使用适用于每个 RDBMS 的解决方案更新了我的问题。
    猜你喜欢
    • 1970-01-01
    • 2018-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-29
    • 2013-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多