设置日期参数,然后确定金额

时间:2015-12-30 21:34:17

标签: sql sql-server

我有两张桌子,我试图把它放在一起,这对我来说有点棘手。我的两个表格是weekstransactions;我创建的以下查询是为了根据他们第一次与我们进行交易来显示所有新客户:

WITH newPat AS
(
    SELECT 
        clinic, patient_id, MIN(date_entered) AS np_date
    FROM 
        transactions
    WHERE 
        impacts = 'P'
    GROUP BY 
        clinic, patient_id
)
SELECT 
    n.clinic, COUNT(n.patient_id) AS new_pats, 
    n.np_date, w.start_week, w.week_id, w.wk_year
FROM 
    newPat n
INNER JOIN 
    weeks w ON (n.np_date BETWEEN w.start_week AND w.end_week)
GROUP BY 
    n.clinic, n.np_date, w.start_week, w.week_id, w.wk_year

因此WITH正在确定patient_id独有的每个clinic的开始日期。然后使用该信息,确定他们进行该交易的给定week_id中的wk_year。这本身就有效。

我还需要从交易表中为那些amount提取patient_id的麻烦,因为它们是新的。无法尝试在WITH中拉出“金额”,否则由于金额不同,它会创建多个条目为“新”。在同一日期,patient_id的给定amount会有多个条目,因为此表显示了各个服务,即使它们属于同一个交易号(tran_num)所以会是什么找到这些数据的最佳方法是什么?

编辑澄清:感谢快速评论,如果在路上进行任何调整,交易ID可以再次发生。我喜欢分区的想法,但我需要的不仅仅是第一行,因为同一个事务和日期可能有多行。我对SQL很新,所以我可能会遗漏一些简单的东西。但是,基本上我需要(SUM(amount) WHERE date_entered = MIN(date_entered))以及patient_id AND clinic唯一的位置。

2 个答案:

答案 0 :(得分:2)

你可以用这个替换你的CTE:

WITH newPat AS(
SELECT clinic, patient_id, date_entered AS np_date, amount,
ROW_NUMBER() OVER (PARTITION BY clinic, patient_id ORDER BY date_entered ASC) AS rn
FROM transactions
WHERE impacts='P'
 )

然后将WHERE rn = 1添加到主查询中。

答案 1 :(得分:0)

使用Tab建议,这是最终结果似乎有效:

WITH newPat AS(
SELECT clinic, patient_id, date_entered AS np_date, SUM(amount) AS total,
ROW_NUMBER() OVER (PARTITION BY clinic, patient_id ORDER BY date_entered ASC) AS rn
FROM transactions
WHERE impacts='P'
GROUP BY clinic, patient_id, date_entered)
SELECT n.clinic, n.patient_id, n.np_date, w.start_week, w.week_id, w.wk_year, n.total
FROM newPat AS n INNER JOIN
dbo.weeks AS w ON n.np_date BETWEEN w.start_week AND w.end_week
WHERE n.rn=1

添加SUM(金额)聚合函数以获得我正在寻找的整体