我对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)。有什么建议吗?
提前致谢!
答案 0 :(得分: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
根据ServiceDate
选择每个合约组的第一行。这种方法的优点是您可以选择所有列而无需使用聚合函数或将其包含在GROUP BY
中。请注意,您至少需要SQLServer 2005。
答案 1 :(得分: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]
答案 2 :(得分: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 demo。