【问题标题】:How can I design a select statement to select a subset of values exclusively based on a condition?如何设计一个 select 语句以仅基于条件选择值的子集?
【发布时间】:2015-11-28 13:38:51
【问题描述】:

我正在尝试设计一个 SQL 语句来仅在某些情况下选择值。这是一个示例来说明我的 2 个输入表和预期输出。

表 1:

TransactionID   TotalItemsType1 TotalItemsType2
0001            1               8
0002            7               6
1234            5               6

表 2:

TransactionID   Cost
0001            5.99
1234            2.25
1234            0.15
0002            9.99

预期结果:

TransactionID   Cost    TotalItemsType1 TotalItemsType2
0001            5.99    1               8
0002            9.99    7               6
1234            2.25    5               6
1234            0.15    0               0

当 Table2 中有多个行用于单个 TransactionID (1234) 时,输出中的 TotalItemsType1/2 列应仅针对具有最高 Cost 值(2.25 与 0.15)的 TransactionID 填充,否则返回 0。如果多个相等的最高值(例如 2.25 与 2.25 相比),则只需根据数据库行顺序选择一个 TransactionID(第一个)。

我尝试过使用各种连接和大小写表达式来做到这一点,但我还没有找到可行的解决方案。

【问题讨论】:

    标签: sql tsql select sql-server-2014 case-when


    【解决方案1】:

    您可以通过 CTE 将分区行号应用于 Table2,然后仅当行号为 1(否则为 0)时,有条件地使用 JOIN 中的值:

    WITH rn AS (
      SELECT *, ROW_NUMBER() OVER(PARTITION BY TransactionID ORDER BY Cost) rn
      FROM Table2
    )
    SELECT rn.TransactionID, rn.Cost, COALESCE(t1.TotalItemsType1, 0) TotalItemsType1,
           COALESCE(t1.TotalItemsType2, 0) TotalItemsType2
    FROM rn LEFT JOIN Table1 t1
      ON rn.TransactionID = t1.TransactionID AND rn.rn = 1
    

    LEFT JOIN 使用行号为 1 的条件为不为 1 的 Table1 生成“空列”。然后COALESCE 使用这些 NULL 值生成所需的 0。

    【讨论】:

      【解决方案2】:
      with max_cost as ( select transactionid tranid,max(cost) max_cost1 from tran_2 group by transactionid)
      select a.transactionid,
             b.cost,
             decode(b.cost,max_cost1,a.totaltype1,0) type_1,
             decode(b.cost,max_cost1,a.totaltype2,0) type_2
      from tran_1 a,tran_2 b,max_cost c 
      where a.transactionid = b.transactionid 
      and c.tranid = a.transactionid 
      and c.tranid = b.transactionid 
      order by a.transactionid
      

      不使用解析函数的解决方案 我使用了包含 transactionid、type1、type2 列的 tran_1 表 以及包含 transactionid、cost 的 tran_2 表

      【讨论】:

        猜你喜欢
        • 2021-01-05
        • 2020-01-18
        • 1970-01-01
        • 2020-10-23
        • 2014-09-16
        • 2015-09-25
        • 1970-01-01
        • 2012-01-26
        • 1970-01-01
        相关资源
        最近更新 更多