如何查询返回不同的ID

时间:2012-03-05 13:16:08

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

我有一个表格,在数据中放置了一些状态。

例如:

表格San_Proposta

Proposta_Id    Status_Id   Imovel_Id
1              1           12
2              1           12
3              3           12
4              4           12
5              5           12

我想在我的表San_Proposta中执行一个返回所有状态等于3,或4或5的Imovel_id的查询。

我的查询返回相同的imovel_id(12),超过一次,因为status_id等于3,4和5到这个imovel_id。如何在我的表san_proposta中使用status_id等于3,4或5的imovel_id时,如何执行此查询?

这只是我想要的一个例子,

我真正的疑问就是这个。

SELECT DISTINCT San_Proposta.Imovel_Id, San_Logradouro.Descricao, San_Endereco.Logradouro, 
San_Imovel.Numero, San_TipoComplemento.Descricao AS Expr1, San_Imovel.Complemento, 
San_Imovel.TipoDsc1, San_Transacao.TransacaoSigla, San_Transacao.Transacao_ID, 
COUNT(San_Proposta.StatusProposta_Id) AS NumeroProposta, 
CASE WHEN SN.ValidaCaptacao = 1 
AND SN.ValidaVenda = 0 
THEN 'AguardandoVenda' ELSE 'Nao' END as FoundInSanNegocio, 
San_Proposta.DataHora 
FROM San_Proposta LEFT JOIN San_Negocio SN 
ON San_Proposta.Proposta_ID = SN.Proposta_ID JOIN San_Imovel 
ON San_Proposta.Imovel_Id = San_Imovel.Imovel_Id JOIN San_Endereco 
ON San_Imovel.Endereco_Id = San_Endereco.Endereco_Id JOIN San_Logradouro 
ON San_Endereco.Logradouro_Id = San_Logradouro.Logradouro_Id JOIN San_TipoComplemento 
ON San_Imovel.TipoComplemento_Id = San_TipoComplemento.TipoComplemento_Id 
JOIN San_Transacao ON San_Imovel.Transacao_ID = San_Transacao.Transacao_ID 
JOIN San_Credenciada ON San_Imovel.Credenciada_Id = San_Credenciada.Credenciada_Id 
WHERE (San_Imovel.Credenciada_Id = 10 OR San_Proposta.Credenciada_Id = 10)
AND San_Proposta.StatusProposta_Id IN (3,4,5,6,7) 
AND San_Proposta.DataHora BETWEEN '20120227' AND DATEADD(day,1,'20120305') 
GROUP BY San_Proposta.Imovel_Id, San_Logradouro.Descricao, San_Endereco.Logradouro, 
San_Imovel.Numero, San_TipoComplemento.Descricao, San_Imovel.Complemento, 
San_Imovel.TipoDsc1, San_Transacao.TransacaoSigla, San_Transacao.Transacao_ID, 
San_Proposta.StatusProposta_Id, SN.ValidaCaptacao, SN.ValidaVenda, San_Proposta.DataHora 
ORDER BY San_Proposta.DataHora DESC 

@Updated

San_Imovel has the Imovel_Id as Primary Key.
San_Proposta has Proposta_Id as Primary Key and Imovel_Id as Foreign Key.
San_Negocio has Negocio_Id as Primary Key and Proposta_Id as Foreign Key.

3 个答案:

答案 0 :(得分:1)

尝试distinct关键字:

select distinct Imovel_Id
from San_Proposta
where Status_Id   in (3,4,5)

select Imovel_Id
from San_Proposta
where Status_Id   in (3,4,5)
group by Imovel_Id

答案 1 :(得分:0)

这有帮助吗?

SELECT distinct Imovel_Id FROM San_Proposta WHERE status_id IN(3,4,5)

答案 2 :(得分:0)

Select Distinct Imovel_id from San_Propsta where status_Id in (3,4,5)