内部联接有3个表和2个总和组

时间:2015-03-09 08:15:35

标签: session

我有3张桌子; COMPANYTRAINING TICKETTEST

COMPANY表:

 COMPANY CODE | COMPANY NAME
 192            ABC ENTERPRISE
 299            XYZ ENTERPRISE

TRAINING TICKET表:

 TICKET ID | COMPANY CODE | START DATE
 2900            192           2015-02-02
 3939            192           2015-03-03
 4399            299           2015-03-02

TEST SESSION表:

 TEST CODE | TICKET ID | COMPANY CODE | CERTIFIED
 1221        2900            192            YES
 2821        3939            192            NULL
 3922        4399            299            YES

我需要这样的东西:

 C. CODE | COMPANY NAME | 1ST START DATE | TRAINING TICKET TOTAL | CERTIFIED TOTAL
 192      ABC ENTERPRISE  2015-02-02             2                1
 299      XYZ ENTERPRISE  2015-03-02             1                1 

可能吗?

我的Sql指令是:

Select *, count(TICKET.CCODE) AS TICKET_TOTAL, count(TEST.CODE) AS CERT_TOTAL
from TICKET 
Inner Join COMPANY on TICKET.CCODE = COMPANY.CCODE 
Inner Join TEST on COMPANY.CCODE = TEST.CCODE 
Group by (TICKET.CCODE),(TEST.CCODE)
Order by TICKET_TOTAL DESC

但两个计数总是等于(TICKET_TOTAL和CERT_TOTAL的结果相同)且总和是错误的 - 结果是TICKET_TOTAL = 21和CERT_TOTAL = 28,但我得到了523 - 对于TOP 1公司。

1 个答案:

答案 0 :(得分:0)

我得到了答案:

Select COMPANY.CODE, COMPANY.NAME, 
MIN(TICKET.STARTDATE), count(TICKET.TICKETID) AS TICKET_TOTAL, 
count(TEST.CERTIFIED) AS CERT_TOTAL
    from COMPANY
    INNER JOIN TICKET ON COMPANY.CODE = TICKET.CCODE 
    LEFT JOIN TEST ON TICKET.TICKETID = TEST.TICKET
    Group by (TICKET.CCODE)
    ORDER BY TICKET_TOTAL DESC 

1-重新排序并为来自COMPANY TABLE的指令加注星标

2分钟(TICKET.STARTDATE)获得第一个开始日期(如果需要,使用MAX获取最后开始日期)

3-将内部联接更改为左联接(因为某些公司在故障单表上有票证,但没有在测试表上进行测试)

希望这可以帮助将来的某个人!