具有sum和唯一输出的SQL查询

时间:2015-10-30 19:19:20

标签: sql sql-server sum unique

让我根据下表中的查询:SQL query with distinct and sum

此表略有编辑:

medley_id   | class    |  color   |   fruit   |   rating
========================================================
1             sweet       red         apple       25
2             sour        blue        pear        5
3             sweet       green       apple       12
4             sour        red         apple       10
5             sour        purple      kiwi        5
6             sweet       purple      kiwi        50
7             sour        blue        kiwi        3
8             sour        blue        pear        9

我想要一个产生这个结果的查询:

class       |   color   |   fruit   |   sum
============================================
(multiple)      red         apple       35
sour            blue        pear        14
sour            blue        kiwi        3
sweet           green       apple       12
(multiple)      purple      kiwi        55

(multiple)不必告诉我多数是多少,它只需要知道它是多重的,但它并不能使行在总和方面是唯一的。

这有意义吗?有人可以帮忙吗?谢谢!

2 个答案:

答案 0 :(得分:1)

我认为这可能会这样做:

SELECT
  CASE
    WHEN COUNT(DISTINCT class) > 1 THEN '(multiple)'
    ELSE MAX(class)
  END AS class
, color
, fruit
, SUM(rating) AS sum
FROM MyTable
GROUP BY color,fruit

未经测试,但应该可以将这个想法变成一个有效的解决方案。

答案 1 :(得分:0)

不使用GROUP BY且仅使用窗口函数:

SELECT DISTINCT
[class] = CASE WHEN 
             DENSE_RANK() OVER (PARTITION BY color, fruit ORDER BY class) 
            +DENSE_RANK() OVER (PARTITION BY color, fruit ORDER BY class DESC) - 1 > 1
              THEN '(multiple)'
              ELSE class
           END
  ,color
  ,fruit
  ,[sum]=  SUM(rating) OVER (PARTITION BY color, fruit)   
FROM #medleys

LiveDemo

输出:

╔════════════╦════════╦═══════╦═════╗
║   class    ║ color  ║ fruit ║ sum ║
╠════════════╬════════╬═══════╬═════╣
║ (multiple) ║ purple ║ kiwi  ║  55 ║
║ (multiple) ║ red    ║ apple ║  35 ║
║ sour       ║ blue   ║ kiwi  ║   3 ║
║ sour       ║ blue   ║ pear  ║  14 ║
║ sweet      ║ green  ║ apple ║  12 ║
╚════════════╩════════╩═══════╩═════╝