在SQL Server中遇到一个查询

时间:2016-05-30 10:25:27

标签: sql sql-server

我有一个名为calci的表。以下是样本数据

CREATE TABLE calci
    (RN int, FREQ int, price int)
;

INSERT INTO calci
    (RN, FREQ, price)
VALUES
    (1, 1, 3),
    (2, 2, 4),
    (3, 3, 5),
    (4, 4, 6),
    (5, 5, 7),
    (6, 6, 8),
    (7, 1, 5),
    (8, 2, 6),
    (9, 3, 9),
    (10, 4, 7),
    (11, 5, 5),
    (12, 6, 1),
    (13, 1, 3)
;

基于freq(1-6)

的总和,我只需要3条记录

结果应该像

price
33 -----sum of first 6 records    
33 -----sum of next six records    
3  -----sum of last six record i.e last record

4 个答案:

答案 0 :(得分:2)

请检查以下查询,以解决上述问题

select sum(price) from calci  group by (rn- freq)

答案 1 :(得分:1)

SELECT SUM(price)
FROM calci
GROUP BY (RN - 1) / 6
HAVING (RN - 1) / 6 IN (0, 1)
UNION
SELECT SUM(price)
FROM calci
WHERE (RN - 1) / 6 = (SELECT (COUNT(*) - 1) / 6 FROM calci)

答案 2 :(得分:1)

我认为你可以使用这样的查询:

;WITH t as (
    SELECT *, CASE WHEN LAG(FREQ) OVER (ORDER BY RN, FREQ) = 6 THEN 1 ELSE 0 END change
    FROM calci
), tt as (
    SELECT *, SUM(change) OVER (ORDER BY RN) grouped
    FROM t)

SELECT SUM(price) sumFreq
FROM tt
GROUP BY grouped;

您可以将change更改为CASE WHEN FREQ - LAG(FREQ) OVER (ORDER BY RN, FREQ) = 1 THEN 0 ELSE 1 END,以便更灵活地处理FREQ;)中的任何跳转。

答案 3 :(得分:1)

尝试这个

;WITH CTE (RN, FREQ, PRICE) AS
    (
    SELECT 1, 1,  3   UNION ALL
    SELECT 2, 2,  4   UNION ALL
    SELECT 3, 3,  5   UNION ALL
    SELECT 4, 4,  6   UNION ALL
    SELECT 5, 5,  7   UNION ALL
    SELECT 6, 6,  8   UNION ALL
    SELECT 7, 1,  5   UNION ALL
    SELECT 8, 2,  6   UNION ALL
    SELECT 9, 3,  9   UNION ALL
    SELECT 10, 4, 7   UNION ALL
    SELECT 11, 5, 5   UNION ALL
    SELECT 12, 6, 1   UNION ALL
    SELECT 13, 1, 3
    ), CTE2(PRICE, RANK) AS
    (
    SELECT (PRICE) , DENSE_RANK () OVER (PARTITION BY FREQ  ORDER BY RN ) FROM CTE 
    )
    SELECT SUM(PRICE) FROM CTE2 GROUP BY RANK