从具有group by子句的多个表中进行选择

时间:2013-10-16 22:49:52

标签: sql sql-server tsql

我的数据库中有这些表:

Ticket 
 -------------------------------
|ID        int              PK  |
|Paid      varchar(50)          |
 -------------------------------

TicketRow
 ----------------------------------
|ID            int              PK |
|TicketID_FK   int                 |
|SHtimeID_FK   int                 |
 ----------------------------------

我想从TicketRow表中获取Ticket表中具有相同SHTiemID_FK且具有Paid='ok'状态的重复行。 我试试这个:

select SHtimeID_FK,count(*) as cnt from dbo.TicketRow
group by SHtimeID_FK
having count(*)>1

但我不知道如何在结果集中添加Ticket表。

更新: 我的结果集中还需要Ticket.ID

1 个答案:

答案 0 :(得分:1)

如果我正确理解您的场景,您可以通过内部联接简单地连接这两个表,因为我认为TicketRow.TicketID_FK是Ticket表的外键。

select SHtimeID_FK,count(*) as cnt 
from dbo.TicketRow as tr inner join dbo.Ticket as t on tr.TicketID_FK=t.ID
where t.Paid='ok'
group by SHtimeID_FK
having count(*)>1