简体   繁体   English

SQL Server简单查询联接表本身

[英]SQL Server Simple Query Joining Table With Itself

I have a table GAMES which holds data about past games played. 我有一张GAMES表格,其中包含有关过去玩过的游戏的数据。 The point of this query is to find all the games that have been played on the same date and print the date, the two teams that played and the result. 该查询的目的是找到在同一日期玩过的所有游戏,并打印日期,参加过的两个团队以及结果。 The table is set up like this: 该表的设置如下:

GAMES 游戏

Home   | Visitors|Date      |Result
-------------------------------------
Bengals| Browns  | 1/1/2012 | Tie
Browns | Bengals | 1/1/2012 | Loss
Giants | Jets    | 4/2/2013 | Win
Giants | Cowboys | 4/2/2013 | Loss
Bears  | Ravens  | 5/3/2012 | Tie
Bills  | Dolphins| 10/11/2014| Win
...

I think the solution is to join the tables in a query similar to this 我认为解决方案是在类似于此的查询中联接表

select 
    A.Date, A.Home, A.Visitors, A.Result
from 
    GAMES as A, GAMES as B
where 
    A.Date = B.Date 
    and A.Home = B.Visitors;

but in this specific query it will only return one game first of all, there are 6 games in total that should show up, and only returns the values from Table A. Is there a way in which I can write the query so it finds all games at once rather than tailoring a specific query to find each one? 但在此特定查询中,它只会首先返回一个游戏,总共应该显示6个游戏,并且仅返回表A中的值。有没有一种方法可以编写查询,以便查找所有内容游戏而不是量身定制一个特定的查询来查找每个游戏? Thanks. 谢谢。

Desired results would be in the form of: 所需的结果将采用以下形式:

1 2012-1-1 Bengals Browns Tie
2 2012-1-1 Browns Bengals Loss
3 2013-4-2 Giants Jets Win
4 2013-4-2 Giants Cowboys Loss
etc. 

Ok, so sound like what you're trying to do is find dates where more than one game occurred. 好的,听起来您要尝试的是查找发生多个游戏的日期。 In that case 在这种情况下

SELECT a.Date, count(*) as CountOfDate
FROM GAMES a
GROUP BY a.Date
HAVING count(*) > 1

How about something like this? 这样的事情怎么样?

SELECT
    A.Date, A.Home, A.Visitors, A.Result
FROM 
    GAMES as A
WHERE EXISTS (SELECT * 
              FROM GAMES as B 
              WHERE A.DATE = B.DATE 
                AND (A.Home <> B.Home 
                OR   A.Visitors <> B.Visitors))
ORDER by A.Date ASC

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM