基于计数,时间范围和位置的查询

时间:2015-04-20 16:14:01

标签: sql tsql

好的,所以我需要编写一个查询,我可能会比它需要的复杂得多,但我可以使用一些帮助。

我需要选择一年或更长时间未见过的客户记录,不止一次见过我们,但如果不在某些地点,则只能看一次。

所以到目前为止我所拥有的是:

WITH CTE AS 
(
SELECT 
    client_id,
    location_id, 
    employee_id,
    create_timestamp, 
    ROW_NUMBER() OVER(PARTITION BY person_id ORDER BY create_timestamp DESC) AS ROW
FROM
    client_Appointment 
)

SELECT 
    c.client_id,
    COUNT(*)
FROM
    CTE AS ce
    INNER JOIN person  AS c
        ON p.person_id= ce.client_id
    INNER JOIN employee_mstr AS em
        ON em.employee_id = ce.empoyee_id
    INNER JOIN location_mstr AS lm
        ON lm.location_id = ce.location_id
WHERE
   ce.create_timestamp <= CONVERT(VARCHAR(10), DATEADD(Year,-1,GETDATE()), 120)
GROUP BY
    p.person_id
HAVING 
    COUNT(*) > 1

我不确定从哪里开始。这也没有得到我需要的所有信息,如果我将这些信息添加到select子句中,我必须在组中使用它,这意味着我没有得到所有需要的记录。 感谢

1 个答案:

答案 0 :(得分:0)

所以你只想要一年或一年以上没见过的客户, 然后客户有一次访问不在某些位置或多次访问。我做对了吗?

注意:只需用表名替换(VALUES(1),(2),(3))

WITH CTE_visits
AS
(
SELECT 
    c.client_id,
    COUNT(*) AS total_visits,
    SUM(
            CASE
                WHEN ce.location_id IN (SELECT ID FROM (VALUES(1),(2),(3)) AS A(ID)) THEN 0 --so when it is a certain location then do NOT count it
                ELSE 1 --if it is not at the certain locations, then count it
            END
        ) AS visits_not_at_certain_locations
FROM
    client_Appointment AS ce
    INNER JOIN person  AS c
        ON p.person_id= ce.client_id
    INNER JOIN employee_mstr AS em
        ON em.employee_id = ce.empoyee_id
    INNER JOIN location_mstr AS lm
        ON lm.location_id = ce.location_id
    CROSS APPLY(SELECT client_id, MAX(create_timestamp) last_visit FROM client_Appointment WHERE client_id = ce.client_id GROUP BY client_id) CA --find most recent visit for each client_id
WHERE
    ce.create_timestamp <= CONVERT(VARCHAR(10), DATEADD(Year,-1,GETDATE()), 120) --remember this only counts visits over a year ago
    AND last_visit <= CONVERT(VARCHAR(10), DATEADD(Year,-1,GETDATE()), 120) --says only return client_id's who's last visit is more than a year ago
GROUP BY
    p.person_id
)

SELECT *
FROM CTE_visits
WHERE   visits_not_at_certain_locations = 1 --seen once NOT at certain locations
        OR total_visits > 1 --seen more than once at any location