【问题标题】:How Can I Rid off Redundant Values from a Column?如何去除列中的冗余值?
【发布时间】:2010-09-24 15:17:00
【问题描述】:

这是示例输出

让我解释一下发生了什么:

查询返回每年的所有发票以及产品 发票中所涉及的。

如您所见,我们在 2010 年有两张发票...发票分别是 30463 和 30516。 发票 30463 有 4 个产品,其运费为 105.88。如你所见 每个产品都会重复运费,这会导致麻烦 我在报告级别计算总和。发票#30463 的 4 个产品有 整体运费105.00。我想要每张发票的每一个运费 无论发票中有多少产品,都只显示一次。我怎样才能实现它?

这里是查询:

SELECT 
      DATEPART(year, CustomerInvDetail.sentDate) AS "Year", 
      CustomerInvoice.cuInvoiceID,  
      Product.productName, 
      CustomerQuoteProducts.unitPrice, 
      CustomerQuoteProducts.qty, 
      CustomerQuoteProducts.qty * CustomerQuoteProducts.unitPrice AS "Price",
      CustomerShipping.shippingPrice
FROM  CustomerInvoice INNER JOIN CustomerInvDetail 
      ON CustomerInvoice.cuInvoiceID = CustomerInvDetail.cuInvoiceID
      INNER JOIN CustomerQuote 
      ON CustomerQuote.customerQuoteID = CustomerInvoice.customerQuoteID
      INNER JOIN CustomerQuoteProducts 
      ON CustomerQuoteProducts.customerQuoteID = CustomerQuote.customerQuoteID
      INNER JOIN CustomerShipping 
      ON CustomerShipping.customerQuoteID = CustomerInvoice.customerQuoteID
      INNER JOIN Customer 
      ON Customer.customerID = CustomerQuote.customerID
      INNER JOIN Product 
      ON CustomerQuoteProducts.productID = Product.productID
WHERE (DATEPART(year, CustomerInvDetail.sentDate) BETWEEN 2001 AND 2022) AND (Customer.customerID = 500)

【问题讨论】:

  • 那么,您的目标是让发票中的 105.00 仅出现一次,而 shippingPrice 中的剩余值显示为零?
  • 您想显示所有产品,但只显示一次价格?或者您只需要每张发票的价格和编号?
  • 因此,对于任何给定的发票编号,您希望运费仅显示在其中一行中吗?哪一行都无所谓,只要它只出现一次?发票的所有其他运费都为零?
  • YES .... 这就是我想要的。

标签: sql sql-server sql-server-2005 tsql sql-server-2008


【解决方案1】:

也许是这样的?

case when row_number() over(partition by cuInvoiceId order by newid()) = 1 then shippingPrice end

更新

它的作用是这样的:

  1. 它根据cuInvoiceId 值将数据划分到分区中
  2. 现在,在这个分区内,我们想枚举每一行,但没有什么可以锚定的,所以我使用了newid(),这基本上意味着随机枚举这些行。
  3. 最后,对于case ... = 1,我希望第一行显示shippingPrice 和所有其他--null

【讨论】:

  • 太棒了!工作...请您简要解释一下这行的作用...我看到了一些新的关键字,例如分区...
【解决方案2】:

当它是第一件商品时,关于运费的案例说明如何?我假设您有一个 lineitem 或某种方式来确定发票上的第一项 - 然后

lineno = 1 然后 CustomerShipping.shippingPrice else 0 end 的情况

【讨论】:

    猜你喜欢
    • 2016-02-28
    • 1970-01-01
    • 2017-08-07
    • 2012-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多