查询中的麻烦

时间:2016-10-26 07:04:52

标签: sql

嘿,我每个人都有这个记录

id  date      hours   groupkey
1   1-12-2016  1        NULL
2   2-12-2016  2        NULL
3   3-12-2016  1        3
4   4-12-2016  1        3 
5   5-12-2016  1        3

我想要这个

id   startdate   enddate     hours
1    1-12-2016   1-12-2016   1
2    2-12-2016   2-12-2016   2
3    3-12-2016   5-12-2016   3

我正在使用此查询

SELECT Max(Isnull(groupkey, id)) AS id, 
       Min(date)                 AS startdate, 
       Max(date)                 AS enddate, 
       Sum(timeoffhours)         AS hours, 
       CASE 
         WHEN Min(groupkey) IS NULL THEN 'No' 
         ELSE 'Yes' 
       END                       Status 
FROM   table 
WHERE  employeekey = 20 
       AND date >= '1/1/2016' 
       AND date <= '12/31/2016' 
GROUP  BY groupkey 

但它为空组键创建一行请帮助我

3 个答案:

答案 0 :(得分:0)

您应GROUP BY Isnull(groupkey, id))在此处解决您的问题。您仍在常规groupkey上进行分组。

答案 1 :(得分:0)

尝试dinamyc表

SELECT id, startdate, enddate, hours, 
         CASE  WHEN mingroup IS NULL THEN 'No' ELSE 'YES'  END as status
  from ( 
        SELECT Max(Isnull(groupkey, id)) AS id, 
               Min(date)                 AS startdate, 
               Max(date)                 AS enddate, 
               Sum(timeoffhours)         AS hours, 
               Min(groupkey)  AS mingroup
        FROM   table 
        WHERE  employeekey = 20 
               AND date >= '1/1/2016' 
               AND date <= '12/31/2016' 
        GROUP  BY groupkey 
  )

答案 2 :(得分:-1)

BEGIN TRAN
CREATE TABLE #Temp (id INT IDENTITY(1,1) , _date DATE ,_hours INT ,  groupkey INT)
CREATE TABLE #OutPutTemp (_id INT , _Startdate DATE ,_EndDate DATE,  _Hours INT)

INSERT INTO #Temp (_date  ,_hours  ,  groupkey )
SELECT '1-12-2016' ,1,NULL UNION ALL
SELECT '2-12-2016' ,2,NULL UNION ALL
SELECT '3-12-2016' ,1,3 UNION ALL
SELECT '4-12-2016' ,1,3 UNION ALL
SELECT '5-12-2016' ,1,3 

INSERT INTO #OutPutTemp(_id  , _Startdate  ,_EndDate,_Hours)
SELECT id , _date , _date , _hours
FROM #Temp
WHERE ISNULL(groupkey,0) = 0

INSERT INTO #OutPutTemp(_id)
SELECT groupkey 
FROM #Temp
WHERE ISNULL(groupkey,0) <> 0
GROUP BY groupkey

UPDATE #OutPutTemp SET _Startdate = Startdate
FROM
(
    SELECT MIN(_date) Startdate ,groupkey
    FROM #Temp
    WHERE ISNULL(groupkey,0) <> 0
    GROUP BY groupkey
)A
WHERE _id = groupkey


UPDATE #OutPutTemp SET _EndDate = EndDate
FROM
(
    SELECT MAX(_date) EndDate ,groupkey
    FROM #Temp
    WHERE ISNULL(groupkey,0) <> 0
    GROUP BY groupkey
)B
WHERE _id = groupkey

UPDATE #OutPutTemp SET _hours = tothours
FROM
(
    SELECT SUM(_hours) tothours ,groupkey
    FROM #Temp
    WHERE ISNULL(groupkey,0) <> 0
    GROUP BY groupkey

)C
WHERE _id = groupkey

SELECT * FROM #OutPutTemp
ROLLBACK TRAN