【问题标题】:sql select - combine the data from the column into one and run distinct on itsql select - 将列中的数据合并为一个并在其上运行不同
【发布时间】:2010-11-08 11:26:35
【问题描述】:

我有一张桌子:

id    coach1    coach2    department    date
1       1         0           txt1       8/11/2010
2       3         0           txt2       1/11/2010
3       1         2           txt1       8/11/2010
4       3         1           txt1       8/11/2010

我想要做的是从两个教练那里得到一列,忽略零并且不重复教练的数字,所以这个例子的输出将是:

coach    department    date
  1          txt1       8/11/2010
  2          txt1       8/11/2010
  3          txt1       1/11/2010

所以我用了:

SELECT id,coach1 as coach,department,date FROM tblWinnings where coach1>0 UNION SELECT id,coach2 as coach,department,date FROM tblWinnings where coach2>0

但现在我需要通过教练栏区分它

我该怎么做?

谢谢!

【问题讨论】:

  • 是否有任何逻辑可以确定 coch 3 应该是来自 id2 的那个还是来自 id4 的那个?我问的原因是他们有不同的部门/日期
  • 您有一个架构错误,应该根据您将coach1 和coach2 作为字段名称的字段来清除。如果您改为使用 N:N 连接表将这些记录链接到教练,您将拥有更简单的 SQL。然而,在 A2010 之前,将连接表限制为每个只有两个教练更加复杂(尽管在引擎级别并非不可能)。

标签: sql ms-access select


【解决方案1】:
select distinct coach1 as coach from tblName
union 
select coach2 from tblName
order by coach

如果您只想要不同的值,请不要使用 Union All(没有 All 子句的联合可防止重复)

由于您不断更新您的问题:如果您想要其他字段的值,您将会遇到问题,因为它们可能会因您使用的字段而异。 (最新的?最早的?随机的?)

【讨论】:

    【解决方案2】:

    我不记得访问的语法,但类似

    select distinct coach from (
    select coach1 as coach from tableX 
    union all 
    select coach2 as coach from tableX) 
    where coach <> 0
    

    【讨论】:

      【解决方案3】:
      create view coaches as
        select coach1 as coach
          from table
         where coach1 <> 0
      union all
        select coach2 as coach
          from table
         where coach1 <> 0;
      
      select distinct coach
        from coaches;   
      

      【讨论】:

      • 无法在 ms 访问中“创建视图”
      • 对 - 那我该怎么办 :-) 实际上我在 ASP 上使用 MS ACCESS DB
      猜你喜欢
      • 2016-04-27
      • 1970-01-01
      • 2018-06-13
      • 2016-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多