创建基于SQL的查看案例

发布于 2025-02-13 21:48:25 字数 238 浏览 1 评论 0原文

我有一个由3列A,B,C的表格,

C列C最初是完全空的,对于每个条目A都有数字或B具有数字(从不在同一行中),

我想创建一个视图,该视图可为每个检查检查行如果a = x和b为null或0,则在col中写入a的值。

例子: “在此处输入图像说明”

有人可以帮助我,我仍然是SQL的新手

I have a table of 3 columns A,B,C

initially column C is completely empty and for every entry either A has a number or B has a number (never both in the same row)

I want to create a view that checks for every row if A=x and B is null or 0 then write the value of A in col.

EXAMPLE:
enter image description here

Can someone help guide me, I am still new to sql

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

仙女 2025-02-20 21:48:25

您可以使用该视图,但是更新

UPDATE mytable 
    SET C = CASE WHEN A > 0 AND (B IS NULL OR B = 0) THEN A 
            ELSE B END

Thsi不会包括发生的情况。 0和b> 0由于您尚未指定要做的事情,因此此查询将始终在B之前进行A

You can'z use a VIEW for that but an UPDATE

UPDATE mytable 
    SET C = CASE WHEN A > 0 AND (B IS NULL OR B = 0) THEN A 
            ELSE B END

Thsi will not include what happens wehen A > 0 and B > 0 as you haven't specify what to do so this query will always take A before B

等你爱我 2025-02-20 21:48:25

正如您提到的,让我们假设具有A,B和C列的表ABC,

create table abc (a     int ,b      int ,c      int )

并且您想根据值将C显示为A或B的值。
然后,您可以通过两种方法创建视图,以实现

  1. 使用情况
 创建视图ABC_V1
作为 
选择a,b,case当isnull(a,0)= 0时,然后b else a end“ c”
从
ABC
 
  1. 使用coce:考虑值是0或某个值,当值为零并使用cocece时,我们可以将列A/B标记为null
 创建视图ABC_V2
作为
选择a,b,coce(nullif(a,0),nullif(b,0))为“ c”
来自ABC
 

否则,
如果要使用Col A/B的值更新C,则

更新ABC
集C = coce(nullif(a,0),nullif(b,0))

Let's assume a table ABC with column A, B and C as you mentioned

create table abc (a     int ,b      int ,c      int )

And you want to display column C as value of either A or B based upon value
then you can create View by two methods to achieve the desired result

  1. Using CASE
create view abc_v1
as 
select a, b, case when isnull(a,0)=0 then b else a end "c"
from
abc
  1. using Coalesce: considering the values would be either 0 or some value, we can mark column A/B as NULL when value is zero and use Coalesce
create view abc_v2
as
select a,b, coalesce(nullif(a,0),nullif(b,0)) as "c"
from abc

Or else,
If you want to update Column C with Value of col A/B then

Update ABC
set c = coalesce(nullif(a,0),nullif(b,0))

べ繥欢鉨o。 2025-02-20 21:48:25

尝试此视图。它阐明了您的要求。

CREATE OR REPLACE VIEW abc_with_c AS
SELECT a, b,
       CASE WHEN a = 0 OR a IS NULL THEN b
            WHEN b = 0 OR b IS NULL THEN a
            ELSE NULL 
        END AS c
  FROM abc;

在SQL中,编写语句是一个好主意,因此它们易于阅读和推理。

Try this view. It spells out your requirement.

CREATE OR REPLACE VIEW abc_with_c AS
SELECT a, b,
       CASE WHEN a = 0 OR a IS NULL THEN b
            WHEN b = 0 OR b IS NULL THEN a
            ELSE NULL 
        END AS c
  FROM abc;

It's a good idea in SQL to write statements so they're easy to read and reason about.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文