【问题标题】:SQL Server - Grouping a column and select Top 1 value from the other column based on the column, which is not included in the T-SqlSQL Server - 对一列进行分组并根据该列从另一列中选择Top 1值,该列不包含在T-Sql中
【发布时间】:2018-09-28 00:18:38
【问题描述】:

我有一个名为 Product 的表,其中包含以下数据:

ParentProduct   Product   Runs  Units
-------------------------------------
    1               5      8     6
    1               5      8     6 
    1               3      7    10
    1               3      8    10
    2               4      8     5
    2               4      8     5

现在我想要基于 ParentProductProduct 分组的分组运行。结果是:

Runs   Units
------------
8       16
8        5
7       10

这意味着,在内部,我们的逻辑应该基于 ParentProductProduct 进行分组,并且应该产生单位的总和。

提前致谢

【问题讨论】:

  • 请贴出你到目前为止所做的事情(你的sql代码)
  • Against ParentProduct - Product, 1 - 3 你运行了 7 和 8,为什么你想只得到 7 个(而不是 8 个)?
  • 如果是ParentProduct、Product求和,为什么1、5返回8 16???不应该是 16 12 吗?

标签: sql sql-server tsql


【解决方案1】:
declare @products table(ParentProduct int, Product int, Runs int, Units int)
    insert into @products 
        select 1,   5,  8,  6 union all
        select 1,   5,  8,  6 union all
        select 1,   3,  7,  10 union all
        select 1,   3,  8,  10 union all
        select 2,   4,  8,  5 union all
        select 2,   4,  8,  5

select runs, units = sum(units)
from(
    select ParentProduct, product, runs, units = sum(distinct units)
    from @products
group by ParentProduct, product, runs) t
group by ParentProduct, runs

【讨论】:

  • 感谢您的宝贵时间。但我想处理动态数据而不是硬编码值。
【解决方案2】:

RunsParentProduct 上对唯一元组进行分组也会得到预期的结果。

SELECT Runs, SUM(Units) as Units
FROM 
(
    SELECT DISTINCT ParentProduct, Product, Runs, Units 
    FROM Product
) AS p
GROUP BY Runs, ParentProduct
ORDER BY Runs DESC, ParentProduct ASC;

【讨论】:

    猜你喜欢
    • 2019-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-30
    • 2021-09-13
    • 2022-11-10
    • 2023-01-18
    相关资源
    最近更新 更多