我有一张表,记录如
id date branch
1001 01/01/2015 VBR
1002 02/05/2015 CBR
1001 03/01/2015 VBr
1005 05/05/2015 CBR
1005 12/12/2015 VBR
1006 05/05/2015 CBR
我需要每月明智地选择记录(日期明智),但它应该是唯一的,否则它不应该在任何其他月份 例如:如果我选择2015年5月,它应该返回1006
答案 0 :(得分:0)
试试这个
SELECT ID FROM
(
SELECT 1001 AS ID, '01/01/2015' AS MY_DATE, 'VBR' AS branch FROM DUAL UNION
SELECT 1002 AS ID, '02/05/2015' AS MY_DATE, 'CBR' AS branch FROM DUAL UNION
SELECT 1001 AS ID, '03/01/2015' AS MY_DATE, 'VBR' AS branch FROM DUAL UNION
SELECT 1005 AS ID, '05/05/2015' AS MY_DATE, 'CBR' AS branch FROM DUAL UNION
SELECT 1005 AS ID, '12/12/2015' AS MY_DATE, 'VBR' AS branch FROM DUAL UNION
SELECT 1006 AS ID, '05/05/2015' AS MY_DATE, 'CBR' AS branch FROM DUAL
)
where LEFT(CONVERT(varchar, MY_DATE,112),6) = '052015'
GROUP BY ID
HAVING COUNT(ID) = 1
答案 1 :(得分:0)
你可以这样试试,
DECLARE @table TABLE
(
id INT,
date1 DATE,
branch VARCHAR(10)
)
INSERT INTO @table
VALUES ('1001',
'01/01/2015',
'VBR'),
('1002',
'02/05/2015',
'CBR'),
('1001',
'03/01/2015',
'VBr'),
('1005',
'05/05/2015',
'CBR'),
('1005',
'12/12/2015',
'VBR'),
('1006',
'05/05/2015',
'CBR')
返回所有记录
SELECT *
FROM @table
WHERE Year(date1) = 2015
AND Month(date1) = 5
返回最新记录
SELECT max(id) id
FROM @table
WHERE Year(date1) = 2015
AND Month(date1) = 5
group by date1