SQL-在公共列上连接表

时间:2016-07-30 23:41:34

标签: sql-server join

此查询:

SELECT CID, count(*) as NumOccurences
FROM Violations
WHERE DateOfViolation BETWEEN (dateadd(day, -30, getdate())) AND getdate()
GROUP BY CID
ORDER BY count(*) DESC;

给出以下结果:

    CID  NumOccurences
    1921    5
    1042    5
    1472    5
    1543    5
    2084    5
    2422    5

NumOccurences经过验证是正确的。由于CID存在于另一个表中,我想将CID绑定到其交集处,即所述其他表Placement[CID,Intersection,...]中的列,并显示该列。

我想要的输出是:

    Intersection        NumOccurences
    Elston and Charles  5
    Diservey and Pkwy   5
    Grand and Chicago   5
    ...
    ...

我试过了:

SELECT Intersection, count(DateOfViolation) as NumOccurences 
FROM Violations
inner join Placement on Violations.CID = Placement.CID
WHERE DateOfViolation BETWEEN (dateadd(day, -30, getdate())) AND getdate()
GROUP BY Intersection
ORDER BY count(*) DESC;

但得到这个结果(不正确):

    Intersection            NumOccurences
    CALIFORNIA AND DIVERSEY 90
    BELMONT AND KEDZIE      83
    KOSTNER AND NORTH       82
    STONEY ISLAND AND 79TH  78
    RIDGE AND CLARK         60
    ROOSEVELT AND HALSTED   60
    ROOSEVELT AND KOSTNER   60

事实上,我不知道我的尝试查询甚至返回了什么或它来自哪里。

修改 运行查询

SELECT CID, count(*) as num
from Placement
where Intersection = 'BELMONT AND KEDZIE'
group by Intersection, Address, CID
order by Intersection, Address, CID

yeilds

CID     num
1372    1
1371    1
1373    1

2 个答案:

答案 0 :(得分:1)

CID和交叉点之间必须存在一对一的关系才能获得您想要的结果。

83实际上是一个素数,这表明不仅Placement表中的BELMONT和KEDZIE交叉点有多个条目,而且还有多个CID对应于该交集。其他交叉点也是如此

试试这个:

SELECT Intersection, CID, count(*) as num
from Placement
-- where Intersection = 'BELMONT AND KEDZIE'
group by Intersection, CID
order by Intersection, CID

这将显示您的Placement表中每个(交集,CID)组合的数量(取消注释where子句以专门查看'Belmont和Kenzie')。然后重新问自己你想要做什么。

答案 1 :(得分:1)

我认为你可以这样做:

SELECT
    MIN(Placement.Intersection) AS Intersection,
    COUNT(DISTINCT Violation.VID /* Violation ID? */) AS NumOccurences 
FROM Violations INNER JOIN Placement ON Violations.CID = Placement.CID
WHERE DateOfViolation
    BETWEEN cast(dateadd(day, -30, getdate()) as date) AND cast(getdate() as date)
GROUP BY Violations.CID
ORDER BY NumOccurences DESC;

还要注意该日期范围。我不确定您是否正在处理datedatetime

您也可以尝试:

SELECT
    (
    SELECT MIN(Intersection) FROM Placement
    WHERE Placement.CID = Violations.CID
    ) AS Intersection,
    COUNT(*) AS NumOccurences
FROM Violations
WHERE DateOfViolation
    BETWEEN cast(dateadd(day, -30, getdate()) as date) AND cast(getdate() as 
GROUP BY CID
ORDER BY NumOccurences DESC;

您可能甚至不需要第二个MIN()