如何根据类似总结列?

时间:2010-12-09 09:23:37

标签: sql group-by inner-join sql-like

我有一个SQL表AddressCount,其中包含3个字段:addressstatenumEntities。我想要做的是根据类似情况得到每个地址+状态组合的numEntities之和。这有点难以描述,但我认为以下相关查询正确地表示了我正在努力实现的目标:

SELECT Address, State, 
    (SELECT SUM(NumEntities)
    FROM AddressCount innerQry 
    WHERE innerQry.address LIKE '%' + outerQry.address + '%' 
        AND innerQry.state = outerQry.state) As NumEntities
FROM AddressCount outerQry

基本上,我希望最终得到一个表,该表具有地址,状态以及所有地址的numEntities总和,例如通配符包围的地址。因此,如果地址是“25 Courtland Rd”并且州是新泽西州,我想得到所有具有NJ状态和地址类似'%25 Courtland Rd%'的行的numEntities。我希望能够通过GROUP BY LIKE来实现这一目标,但我认为这不可能通过SQL实现。基本概念是完成这样的事情:

SELECT address, state, sum(numEntities)
FROM AddressCount
GROUP BY (LIKE '%' + address + '%')

我上面发布的相关查询sql语句看起来很准确,但是如果可能的话,我想通过表的内部联接来完成同样的事情。我最近读到可以在LIKE表达式上连接表,所以我想完成以下内容:

SELECT t1.Address, t1.State, SUM(t2.NumEntities)
FROM AddressCount t1
INNER JOIN AddressCount t2
    ON t1.state = t2.state
    AND t2.address LIKE '%' + t1.address + '%'

这似乎不起作用,但是......任何想法我怎么能做到这一点?

4 个答案:

答案 0 :(得分:3)

如果我理解正确,添加GROUP BY t1.state, t1.address应该有效。

答案 1 :(得分:2)

你只需要添加

GROUP BY t1.Address, t1.State

...在第二次查询结束时。刚刚对PostgreSQL进行了快速测试,结合LIKE和GROUP BY按预期工作,所以我认为没有理由在你的情况下。

答案 2 :(得分:0)

也许:
SELECT x.state,x.address,SUM(x.NumEntities)
FROM(SELECT * FROM AddressCount WHERE address LIKE%)x
GROUP BY x.state

答案 3 :(得分:0)

你可以试试这个吗?

SELECT a.Address,t.State,t.numEntities
FROM
  dbo.AddressCount a,
        (SELECT     State,SUM([Count]) as numEntities
        FROM dbo.AddressCount
        WHERE Address LIKE '%+address+%' 
        GROUP BY State ) t
WHERE a.State = t.State