如何在sql server中一起使用count,case和Distinct

时间:2016-05-06 08:56:56

标签: sql-server stored-procedures

我想创建一个声明,但我没有成功完成此操作。请你看看,让我知道我需要做些什么来完成这个。我的问题是如何在我的查询中添加这两部分。

  

我想查看每个DRV1NUM的最近30天的订单。如果该驱动程序已工作0天,则说“非活动”。如果司机工作超过15天,那么“全时”和不到15天就是“兼职”。

     

在这一篇中,我想查看最近30天的订单,并将DRIVERNUM的左(4)与整个DRIVERNUM进行比较。在某些情况下,我们有左侧后面有第5个字母的驱动程序4.我想查看订单的最后30天,如果左边(4)DRV1NUM在查看所有字符时有多个DRV1NUM,那么SAY '主'

     SELECT DISTINCT DRVLICNUM,DOB,COUNTRY,CREDITLIMIT,DRIVERNUM=LEFT(DRIVERNUM,4),
        SSN,D.VEHICLE,PHN1,DRVLICST,HOST,VEHICLE_MC,
        VEHICLE_DOT,BACK_APPROVED=CASE WHEN PROBDATE IS NOT NULL THEN 'YES' ELSE 'NO' END

     -- CASE WHEN COUNT(DISTINCT O.DROPDATE)=0 IN LAST 30 DAYS THEN 'NOT ACTIVE' WHEN COUNT(DISTINCT O.DROPDATE)>15 IN LAST 30 DAYS THEN 'FULL TIME'  WHEN COUNT(DISTINCT O.DROPDATE)>=1 AND <=15 THEN 'PART TIME' IN LAST 30 DAYS ELSE NULL AS DAYSWORKED,

-- --CASE WHEN COUNT(DISTINCT O.DRV1NUM OF LEFT(DRIVERNUM,4 )>0 IN LAST 30 DAYS OF ORDERS>1 THEN 'MASTER IC' ELSE NULL AS MASTER

/* ABOVE TWO STATEMENT I WANT TO ADD */ 
        FROM DRIVER D

        FULL OUTER JOIN orde_ O ON O.DRV1ID=D.DRIVERID
        AND ISNUMERIC(DRIVERNUM)=1 and DRIVERNUM NOT IN ('1010')

我想要的预期输出

DRVLICNUM    Employee    DOB       COUNTRY    ACTIVESTATUS  
---------------------------------------------------------
055243324    CONTRACTOR 1985-04-13 ATLANTA    FULL TIME

此处ActiveStatus处于活动状态,因为驱动程序在过去15天内工作超过15天,或者如果它将少于15天,那么它将是“兼职”

2 个答案:

答案 0 :(得分:1)

我无权访问您分享的Google直播链接。

但是,您必须使用CTE(公用表表达式)来获取天数,然后使用它计算ActiveStatus列的值。

尝试使用以下代码:

;
WITH CTE1
AS(
    SELECT D.DRIVERID,
        COUNT(DISTINCT O.DROPDATE) AS DayCount
    FROM DRIVER AS D
    LEFT JOIN ORDER AS O ON D.DRIVERID=O.DRV1ID AND O.DROPDATE BETWEEN CONVERT(DATE,DATEADD(DAY,-30,GETDATE())) AND GETDATE()
    WHERE ISNUMERIC(D.DRIVERNUM)=1 AND D.DRIVERNUM NOT IN ('1010')
    GROUP BY D.DRIVERID
)
SELECT  DRVLICNUM,DOB,COUNTRY,CREDITLIMI,...
        CASE 
            WHEN DayCount=0 THEN 'NOT ACTIVE'
            WHEN DayCount<=15 THEN 'PART TIME'
            WHEN DayCount>=30 THEN 'FULL TIME'
        END AS ACTIVESTATUS         
FROM CTE1 AS C
JOIN DRIVER AS D ON C.DRIVERID=D.DRIVERID

答案 1 :(得分:0)

这是第一个的两个siple查询:

1)按日期和按驱动程序分组选择顺序(如果每天不超过一个订单):

select o.DRIVERID
    , count(*) as cnt
  from orde_ o
  where o.DROPDATE betwen GETDATE() AND DATEADD(DAY,-30,GETDATE())
  group by o.DRIVERID

2)选择驱动程序并加入分组订单

select case 
      when o.ctn >= 15 then 'FULL TIME'
      when o.ctn > 0 then 'PART TIME'
      else 'NOT ACTIVE'
    end
    , <other fields you want>
  from DRIVER as D
  left join <query above> as o
    on o.DRIVERID = d.DRIVERID

第二个:

select left(d.DRIVERID, 4), count(*) as cnt
  from DRIVER as D
  group by left(d.DRIVERID, 4)
  having count(*) > 1

并加入它,如果不为null则比较整个id