SQL基于条件的行选择

huangapple go评论68阅读模式
英文:

SQL Row Select Based on Condition

问题

在MSSQL中,你可以使用以下SQL语句来实现你的需求:

SELECT TOP 1
    LineStatus,
    SUM(OrderQty) AS TotalOrderQty
FROM
    YourTableName
WHERE
    LineStatus IN (80, 10)
GROUP BY
    LineStatus
ORDER BY
    CASE
        WHEN LineStatus = 80 THEN 1
        ELSE 2
    END;

这将会首先选择具有LineStatus为80的行并计算OrderQty的总和。如果没有符合条件的行,它会选择LineStatus为10的行并计算OrderQty的总和。

请将上述YourTableName替换为你实际使用的表格名。

希望对你有所帮助!

英文:

I am trying to find a way to select a row based on condition in MSSQL, I have two rows

SO LineNumber LineStatus OrderQty
A 1 10 4
A 1 80 4

How should I write in SQL -- First Select the row with line status 80 and SUM(OrderQty), if there is no such row with Line Status = 80 then select Line Status= 10 and SUM(OrderQty).

Can you please suggest something, Thanks in advance

I have tried AND OR condition, not working as expected. Can you kindly suggest something to help me.

答案1

得分: 0

我喜欢在这种情况下使用连接:

       SELECT *
       FROM table1 t1
       JOIN table2 t2 
          ON t2.id = (
           SELECT TOP 1 id
           FROM table2 innerT2
           WHERE innerT2.condition = condition
       )
英文:

I like to use a join for such a thing:

   SELECT *
   FROM table1 t1
   JOIN table2 t2 
      ON t2.id = (
       SELECT TOP 1 id
       FROM table2 innerT2
       WHERE innerT2.condition = condition
   )

答案2

得分: 0

这个对你是否有效?

选择 LineStatus, SUM(OrderQty) 作为 SumOrder
 _1
分组按 LineStatus
 LineStatus 降序排序
英文:

Would this work for you?

select LineStatus, SUM(OrderQty) as SumOrder
from Table_1
group by LineStatus 
order by LineStatus desc

答案3

得分: 0

选择 
  SO
, 使用 coalesce(SUM(case when LineStatus=80 then OrderQty end)
          ,SUM(case when LineStatus=10 then OrderQty end)) as SumOrder
从 Table_1
按 SO 分组
英文:

Can we assume that you are grouping by SO? If so, something like this should work:

select 
  SO
, coalesce(SUM(case when LineStatus=80 then OrderQty end)
          ,SUM(case when LineStatus=10 then OrderQty end)) as SumOrder
from Table_1
group by SO

huangapple
  • 本文由 发表于 2023年4月11日 05:24:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/75980854.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定