将总价格的总和添加到按ID分组的每一行

时间:2014-04-16 17:57:48

标签: sql sql-server sql-server-2008-r2

我有一个查询,需要进行一系列药品交易,并根据drugPrices表格为每笔交易定价:

    SELECT      
        fi.facilityIndividualId,
        fi.lastName + ',' + fi.firstName as 'Patient Name',
        ddh.drugName,
        CAST((ddh.dosesGiven * a.drugPrice) as decimal(9,2)) as 'Price' 
    FROM
        drugDistributionHistory ddh 
        INNER JOIN facilityIndividuals fi on ddh.facilityIndividualId = fi.facilityIndividualId 
        INNER JOIN drugPrices ON ddh.drugName like '%' + a.drugName + '%'
    ORDER BY
        fi.lastName + ', ' + fi.firstName,
        ddh.drugName    

我的结果看起来像这样:

39491   Martinez,Spring Celexa      0.06
39491   Martinez,Spring Seroquel    0.16
16884   McDannell,Chris Glucophage  0.03
69275   Riemer,Joseph   Folic Acid  0.01
69275   Riemer,Joseph   Paxil       0.07
17070   Savage,William  Asprin EC   0.01
17070   Savage,William  Lopressor   0.02

我想要添加到我的查询中的是每行的总计列,分组在facilityIndividualId上,因此我的结果如下所示:

39491   Martinez,Spring Celexa      0.06   0.22
39491   Martinez,Spring Seroquel    0.16   0.22
16884   McDannell,Chris Glucophage  0.03   0.03
69275   Riemer,Joseph   Folic Acid  0.01   0.08
69275   Riemer,Joseph   Paxil       0.07   0.08
17070   Savage,William  Asprin EC   0.01   0.03
17070   Savage,William  Lopressor   0.02   0.03

如何实现这一目标?

2 个答案:

答案 0 :(得分:3)

SQL Server您可以使用聚合函数(SUMCOUNT等...),然后OVERPARTITION BY来实现内联结果

    SELECT      
        fi.facilityIndividualId,
        fi.lastName + ',' + fi.firstName as 'Patient Name',
        ddh.drugName,
        CAST((ddh.dosesGiven * a.drugPrice) as decimal(9,2)) as 'Price',
        SUM(CAST((ddh.dosesGiven * a.drugPrice) as decimal(9,2))) OVER (PARTITION BY fi.facilityIndividualId) as 'Total'
    FROM
        drugDistributionHistory ddh 
        INNER JOIN facilityIndividuals fi on ddh.facilityIndividualId = fi.facilityIndividualId 
        INNER JOIN drugPrices ON ddh.drugName like '%' + a.drugName + '%'
    ORDER BY
        fi.lastName + ', ' + fi.firstName,
        ddh.drugName 

答案 1 :(得分:3)

那么,我要做的是使用子查询或CTE来汇总每个客户ID的单位价格,然后将客户ID加入到其余客户ID中。

CREATE TABLE #testcase(
p_id int,
a_description varchar(20),
unit_price float
)

INSERT INTO #testcase
VALUES (1, 'drug 1', .39)

INSERT INTO #testcase
VALUES (1, 'drug 2', .13)

INSERT INTO #testcase
VALUES (2, 'drug 44', 5.59)

INSERT INTO #testcase
VALUES (2, 'drug x', 1.39)

INSERT INTO #testcase
VALUES (3, 'drug x', 1.39)

INSERT INTO #testcase
VALUES (3, 'drug x12', 11.39)

INSERT INTO #testcase
VALUES (3, 'drug zz', 12.09)



SELECT 
t.p_id
,t.a_description
,t.unit_price
,x.unit_price
FROM #testcase t
JOIN (
    SELECT 
        p_id
        ,SUM(unit_price) AS [unit_price]
    FROM #testcase t 
    GROUP BY p_id
        ) AS x ON x.p_id = t.p_id

Aducci的回答更好,使用OVER PARTITION BY是一种更简洁的方法。

但是,既然我不愿意这样做,我想我还是会发布我的。

干杯