1

我对 SQL 很陌生,所以如果我遗漏了明显的内容,请提前道歉。

我的数据包括客户合同号、服务日期和价格清单。我需要能够按客户分组,按服务日期拉第一个价格,并在另一列中有所有价格的总和。

所以我有类似的东西:

SELECT
CONTRACT, 
SUM(PRICES) as [TOTAL SPENT]
FIRST(PRICE) as [FIRST PRICE]
FROM TABLE
GROUP BY CONTRACT
ORDER BY CONTRACT

但显然 First 不是内置函数名(我使用的是 Microsoft SQL Server)。有什么建议么?

提前致谢!

4

3 回答 3

2

您可以使用ROW_NUMBER

WITH CTE AS(
    SELECT CONTRACT, 
           SUM(PRICES) OVER(PARTITION BY CONTRACT) as [TOTAL SPENT],
           PRICE as [FIRST PRICE],
           ROW_NUMBER()OVER(PARTITION BY Contract Order By  ServiceDate) 
    FROM TABLE
)
SELECT CONTRACT, [TOTAL SPENT], [FIRST PRICE]
FROM CTE
WHERE RN = 1
ORDER BY CONTRACT

这会根据 . 从每个 Contract-group 中选择第一行ServiceDate。这种方法的优点是您可以选择所有列,而无需使用聚合函数或将其包含到GROUP BY. 请注意,您至少需要 SQLServer 2005。

于 2013-07-30T15:36:45.497 回答
1

尝试:

    -- @tmp represents your table
    declare @tmp table (
     [Contract] int,
     [Prices] decimal(18,5),
     [ServiceDate] datetime
    )

    -- some testing data - you may skip that
    insert into @tmp values(1, 100, '2011-01-01')
    insert into @tmp values(1, 200, '2011-01-02')
    insert into @tmp values(2, 10, '2011-01-01')
    insert into @tmp values(2, 20, '2011-01-02')
    insert into @tmp values(2, 30, '2011-01-03')


    SELECT
      [CONTRACT], 
      SUM(PRICES) as [TOTAL SPENT],
      (SELECT TOP 1 t2.PRICES FROM @tmp t2 
       WHERE t2.[Contract] = t1.[Contract] 
       ORDER BY [SERVICEDATE]) as [FIRST PRICE]
    FROM @tmp t1
    GROUP BY [CONTRACT]
    ORDER BY [CONTRACT]
于 2013-07-30T15:38:22.320 回答
0

像这样的东西:

SELECT
    CONTRACT, 
    SUM(PRICE) as [TOTAL SPENT],
    (SELECT TOP 1 PRICE FROM [TABLE]
     WHERE CONTRACT_DATE = MIN(T.CONTRACT_DATE)
     AND   CONTRACT = T.CONTRACT) AS [FIRST PRICE]
    FROM [TABLE] T
    GROUP BY CONTRACT
    ORDER BY CONTRACT

请参阅SQL Fiddle 演示

于 2013-07-30T15:42:39.800 回答