独特的记录

时间:2017-10-18 14:45:06

标签: sql tsql sql-server-2012

有人可以告诉我如何摆脱欺骗,但保留我的结果集中的列? 我简化了查询,所以应该可以阅读。

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

我希望得到这个结果集,只有max(Date):

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

有人可以添加到我的查询中,所以我可以把它作为一个例子,我已经多次遇到这个问题,我甚至在这里问过,但仍然无法正确实现它。这可能是清晰而简单的查询,其中我基本上想要具有最新日期的唯一ID,但包括所有期望的列赢得我的结果集。非常感谢你。

1 个答案:

答案 0 :(得分: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