【问题标题】:SELECT using a case statement使用 case 语句选择
【发布时间】:2015-07-14 12:29:32
【问题描述】:

下午好

我是 SQL Server 的新手,正在努力构建我的选择。我正在寻找一些建议,因为我不知道该转向哪里。

因此,如果列存在于其他表中,我需要更新一个表。然而,另一个表可能只有一个默认值 999,这意味着任何值。我会尝试编写 sudo 代码。

select row
from master table
where between dates
and cust is in ( custtable where cust matches or cust from custtable = 999)
and branch is in ( branchtable where branch matches or branch from branchtable = 999)
and product is in ( producttable where product matches or product from producttable = 999)

只有当 3 等于被找到时,我才应该拥有该行。

请让我知道您需要更多信息,因为这可能没有意义

提前致谢。放轻松,我只是在学习

更新

所以我有以下

select @SI_Id = SIC_IdSupportedInitiative, @SI_SuppId = SIC_IdSupplier,
 @sd = SIC_StartDate, @ed = SIC_EndDate, @SI_Amt = SIC_ClaimAmount
from SIC_SupportedInitiative
where SIC_IdSupportedInitiative = 1

select sc.ID, sc.[Actual Posting Date],sc.[Customer Account], 
 sc.[Accounting Branch],sc.[Product Code],sc.[SalesQ uantity],sc.SIC_TotalClaimAmount
From SalesCurrent sc
where sc.[Actual Posting Date] between @sd and @ed
and exists 
( select 1 from SIC_CustomerDetails c
    where c.SIC_IdSupportedInitiative = @SI_id
      and c.SIC_ICC_Customer = sc.[Customer Account] or c.SIC_ICC_Customer = 999 )
and exists
( select 1 from SIC_BranchDetails b
    where b.SIC_IdSupportedInitiative = @SI_id
      and b.SIC_IMO_Branch = sc.[Accounting Branch] or b.SIC_IMO_Branch = 999 )
and exists
( select 1 from SIC_ProductDetails p
    where p.SIC_IdSupportedInitiative = @SI_id
      and p.SIC_SupplierProductCode = sc.[Product Code] or 
          p.SIC_SupplierProductCode IN (SELECT sp.SIC_SupplierProductCode 
                                          FROM SIC_SupplierProducts sp 
                                         WHERE sp.SIC_IdSupplier = @SI_SuppId 
                                           AND sp.SIC_SupplierProductCode = sc.[Product Code])
)

then I was going to loop round as I need to update the SIC_TotalClaimAmount 

to be SIC_TotalClaimAMount = SIC_TotalClaimAmount + ( sc.[Sales Quantity] * @SI_Amt )

如果有更简单的方法很想听。

谢谢

【问题讨论】:

  • 如果你想更新你的表,为什么要使用select

标签: sql sql-server select case


【解决方案1】:

我不知道查询的其余部分是什么样的,但您可以使用exists 执行您想要寻找的逻辑:

from mastertable mt
where between dates and
      exists (select 1 from custtable c where c.cust = mt.cust or c.cust = 999) and
      exists (select 1 from branchtable b where b.branch = mt.branch or b.branch = 999) and
      exists (select 1 from producttable p where p.product = mt.product or p.product = 999) 

【讨论】:

  • 太棒了。非常感谢。最后一个问题。在产品表上,如果产品是 999 那么它应该检查另一个表以查看该行是否存在?再次感谢您。
  • @Sip 。 . .那是另一个问题。问题应该作为问题提出,而不是在评论中提出。我建议在新问题中包含示例数据和所需结果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 2015-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多