我尝试使用CASE / WHEN来解决下面的问题,但我一直在寻找确切的解决方案。以下是预期结果后面的问题。需要你的帮助。
考虑下表EmpComp
NAME COMPANY START_DATE END_DATE IS_ACTIVE
-----------------------------------------------------------------------
Kiran TCS 01-Apr-2015 31-May-2015 0
Kiran TCS 15-Apr-2015 31-May-2015 1
Kiran TCS 15-Jun-2015 30-Jun-2015 1
Mike ABC 01-Jan-2015 31-Jan-2015 0
Mike ABC 01-Feb-2015 31-Mar-2015 0
Pawan XYZ 01-Dec-2015 31-Dec-2015 1
结果应为:结果表再次解释逻辑。
NAME COMPANY START_DATE END_DATE IS_ACTIVE
-----------------------------------------------------------------------
Kiran TCS 15-Apr-2015 30-Jun-2015 1 (only the records with 1 are considered and start_date, end_date should cover the complete end to end range for is_active = 1, incld any gap days.
Mike ABC 01-Feb-2015 31-Mar-2015 0 (when all the grouped records have is_active = 0, only the last one is shown)
Pawan XYZ 01-Dec-2015 31-Dec-2015 1
或
NAME COMPANY START_DATE END_DATE IS_ACTIVE
-----------------------------------------------------------------------
Kiran TCS 15-Apr-2015 30-Jun-2015 1 (same logic as above for some of grouped records with is_active = 1)
Mike ABC 01-Jan-2015 31-Jan-2015 0 (it is ok to show all the grouped records that have all 0s for is_active)
Mike ABC 01-Feb-2015 31-Mar-2015 0
Pawan XYZ 01-Dec-2015 31-Dec-2015 1
逻辑:
答案 0 :(得分:2)
将聚合函数与CASE
表达式一起使用:
SELECT
Name,
Company,
Start_Date =
CASE
WHEN SUM(CASE WHEN Is_Active = 1 THEN 1 ELSE 0 END) > 0
THEN MIN(CASE WHEN Is_Active = 1 THEN Start_Date END)
ELSE
MAX(Start_Date)
END,
End_Date =
CASE
WHEN SUM(CASE WHEN Is_Active = 1 THEN 1 ELSE 0 END) > 0
THEN MAX(CASE WHEN Is_Active = 1 THEN End_Date END)
ELSE
MAX(End_Date)
END,
Is_Active =
CASE
WHEN SUM(CASE WHEN Is_Active = 1 THEN 1 ELSE 0 END) > 0 THEN 1
ELSE 0
END
FROM #EmpComp
GROUP BY
Name, Company
ORDER BY
Name, Company
答案 1 :(得分:0)
您可以使用view和Union Query
来完成1:创建包含1
记录的视图**
Create View My_View as
Select NAME,COMPANY,MIN(STAR_DATE) as START_DATE ,MAX(END_DATE) as END_DATE
From MY_TABLE
Where IS_ACTIVE=1 group by NAME,COMPANY
**
MY_VEW包含有1的记录,实际上每次都是一个表 你的桌子改变了原子改变的
2:使用UNION生成2个SQLS
2.1 :The first display records from our view .
2.2: Second display records with 0 that their key not exist in our view
**
Select * from My_View (First Query
(In case that you do not want all records in view you can use where exactly like table)
Union
Select A. NAME,A.COMPANY,A.START_DATE,A.END_DATE
from My_Table as A left join MY_View as B on A.Name=B.NAME
And A.COMPANY=B.COMPANY where B.NAME IS NULL and B.COMPANY IS_NULL
**