2017-10-18 106 views
-1

有人可以告訴我如何擺脫困惑,但保留在我的結果集的列? 我簡化了查詢,所以應該可以閱讀。不同的記錄

SELECT 
cst_recno as 'ID', 
ind_first_name as 'First', 
ind_last_name as 'Last', 
cmt_code as 'Code', 
cmt_name as 'Com.Name', 
ixe_add_date as 'Date' 
FROM 
mb_committee_x_customer 
JOIN co_customer ON cst_key=cmc_cst_key 
JOIN mb_committee ON cmt_key=cmc_cmt_key 
JOIN co_individual ON ind_cst_key=cmc_cst_key 
LEFT JOIN mb_committee_x_position ON cop_key = cmc_cop_key 
LEFT JOIN mb_committee_type ON cmt_ctp_code = ctp_code 
LEFT JOIN mb_committee_position ON cpo_key=cop_cpo_key 
LEFT JOIN co_customer_x_address ON cmc_cxa_key=cxa_key 
LEFT JOIN co_address ON cxa_adr_key = adr_key 
LEFT JOIN co_individual_x_expertise_area ON ixe_ind_cst_key = cst_key 
LEFT JOIN co_expertise_area on exa_key = ixe_exa_key 
WHERE cmt_ctp_code = N'Council' AND cmc_end_date >= getdate() AND ind_deceased_flag != 1 and cst_recno = '782131' 
order by ind_last_name asc 

結果集:

ID  First Last Code    Com.Name    Date 
782131 Jeffrey Ball MFCSILVER Multi-Family Council 2017-07-20 12:10:44.000 
782131 Jeffrey Ball MFCSILVER Multi-Family Council 2017-07-20 12:10:05.000 
782131 Jeffrey Ball MFCSILVER Multi-Family Council 2017-07-20 12:10:15.000 
782131 Jeffrey Ball MFCSILVER Multi-Family Council 2017-07-20 12:11:10.000 
782131 Jeffrey Ball MFCSILVER Multi-Family Council 2017-07-20 12:10:25.000 
782131 Jeffrey Ball MFCSILVER Multi-Family Council 2017-07-20 12:10:56.000 
782131 Jeffrey Ball MFCSILVER Multi-Family Council 2017-07-20 12:11:21.000 

我想獲得這個結果集,而不是隻最大(日期):

ID  First Last Code    Com.Name    Date 
782131 Jeffrey Ball MFCSILVER Multi-Family Council 2017-07-20 12:11:21.000 

可有人請添加到我的查詢,所以我可以把它作爲一個例子,我已經遇到過這個問題多次,我甚至在這裏問過,但仍然無法正確實施它。這可能是清楚而簡單的查詢,我基本上想要最新日期的唯一ID,但包括所有期望的列贏得我的結果集。非常感謝你。

+1

查找最大和組通過使用....噸,就在這裏爲例子。 – Twelfth

+0

[在一個表中由最大日期過濾的重複行的SQL查詢]的可能重複(https://stackoverflow.com/questions/23476055/sql-query-of-duplicate-rows-filtered-by-max-date-within -one-table) –

回答

0

使用MAXGROUP BY,添加你需要的任何領域GROUP BY

SELECT 
cst_recno as 'ID', 
ind_first_name as 'First', 
ind_last_name as 'Last', 
cmt_code as 'Code', 
cmt_name as 'Com.Name', 
MAX(ixe_add_date) as 'Date' 
FROM 
mb_committee_x_customer 
JOIN co_customer ON cst_key=cmc_cst_key 
JOIN mb_committee ON cmt_key=cmc_cmt_key 
JOIN co_individual ON ind_cst_key=cmc_cst_key 
LEFT JOIN mb_committee_x_position ON cop_key = cmc_cop_key 
LEFT JOIN mb_committee_type ON cmt_ctp_code = ctp_code 
LEFT JOIN mb_committee_position ON cpo_key=cop_cpo_key 
LEFT JOIN co_customer_x_address ON cmc_cxa_key=cxa_key 
LEFT JOIN co_address ON cxa_adr_key = adr_key 
LEFT JOIN co_individual_x_expertise_area ON ixe_ind_cst_key = cst_key 
LEFT JOIN co_expertise_area on exa_key = ixe_exa_key 
WHERE cmt_ctp_code = N'Council' AND cmc_end_date >= getdate() AND ind_deceased_flag != 1 and cst_recno = '782131' 
GROUP BY cst_recno , 
ind_first_name , 
ind_last_name , 
cmt_code , 
cmt_name 
order by ind_last_name asc 
+0

太棒了,非常感謝你 – klima

+0

請標記爲已回答 –