我怎么能做一个分组

时间:2012-03-07 16:38:31

标签: sql-server sql-server-2008 tsql

我可以向房子做很多请求,但只能接受一个请求。如果请求被接受,请求将保存在我的San_Negocio表中。在我的表San_Proposta中,我保存了请求。

我想进行查询以获取san_proposta中状态等于1的所有数据,并且san_proposta中所有状态等于2但在san_negocio中的所有数据的ValidaVenda与ValidaCaptacao不同

San_Proposta

Proposta_Id    Imovel_Id    DataHora                Status
1              2001         2012-03-07 00:00:00     1
2              2001         2012-03-07 00:00:01     1
3              2001         2012-03-07 14:00:00     2
4              2001         2012-03-07 15:00:00     1
5              2002         2012-03-07 00:00:00     1
6              2002         2012-03-07 00:00:02     1

San_Negocio

Negocio_Id     Imovel_Id    Proposta_Id   ValidaVenda    ValidaCaptacao
1              2001         3             0              1

我想要什么

Imovel_Id    Number Of Propost With status 1
2001         3
2002         2

我正在尝试此查询,但问题是返回。 Imovel_Id重复,因为我的DataHora在每个Request(Proposta_Id)中都不同。

SELECT p.Proposta_Id 
FROM San_Proposta p 
WHERE p.StatusProposta_Id = 1 

UNION 

SELECT p.Proposta_Id 
FROM San_Proposta p 
LEFT JOIN San_Negocio 
ON San_Negocio.Proposta_Id = p.Proposta_Id 
WHERE p.StatusProposta_Id = 2 
AND San_Negocio.ValidaCaptacao <> San_Negocio.ValidaVenda

2 个答案:

答案 0 :(得分:4)

我没有对此进行测试,但它看起来像这样:

select Imovel_Id, count(*) as "Number Of Propost With status 1" 
FROM San_Proposta 
WHERE Imovel_Id=2001 and Status=1
GROUPBY Imovel_Id

更新:

select Imovel_Id, count(*) as "Number Of Propost With status 1" 
FROM San_Proposta p LEFT OUTER JOIN San_Negocio n ON p.Imovel_Id=n.Imovel_Id
WHERE p.Status=1
GROUPBY Imovel_Id

然后,您可以通过更新where:

继续评估where子句中的任何其他列

在哪里p.Status = 1而p.StatusProposta_Id = 2

对于sqlServer

,左外连接的语法可能不同

答案 1 :(得分:0)

SELECT sn.Imovel_Id,COUNT(sn.Proposta_Id) as Count_Proposta_status
FROM San_Proposta sp,San_Negocio sn
WHERE sp.Imovel_Id = sn.Imovel_Id
AND sp.Imovel_Id=2001
AND sp.Status = 1
AND sn.Proposta_Id is NOT NULL 
GROUP BY sn.Imovel_Id;