gpt4 book ai didi

sql - 如何在 SQL 中创建 bool 计算字段并加入该计算字段?

转载 作者:行者123 更新时间:2023-12-04 23:46:17 25 4
gpt4 key购买 nike

首先检查这段代码。我似乎应该对我有用,但事实并非如此! (惊喜!)

无论如何,这是我首先尝试的:

SELECT
Status as status,
Address as ip,
PCName as pc_name,
(Numbers.Phone = 'CPU/' + PCName) as cpu_contact,
(Numbers.Phone = 'PC/' + PCName) as pc_contact,
(Numbers.Phone = 'LOGIN/' + PCName) as login_contact,
FROM IPAddress
WHERE $where --Generated In code
JOIN Numbers
ON ('CPU/' + PCName = Numbers.Phone)
OR ('PC/' + PCName = Numbers.Phone)
OR ('LOGIN/' + PCName = Numbers.Phone)

所以我想要的是一些 bool 计算字段并在类似条件下加入。我还希望结果折叠成单行。例如,我认为当前的设置会做这样的事情:

status ip  cpu_contact pc_contact login_contact
-----------------------------------------------
foo bar true false false
foo bar false true false
foo bar false false true

显然我更愿意

status ip  cpu_contact pc_contact login_contact
-----------------------------------------------
foo bar true true true

有什么想法吗?数据库重新设计不是一种选择。如果是的话,我会那样做:-)

最佳答案

您可以使用 GROUP BYSUM 来折叠行:

SELECT
Status as status, Address as ip, PCName as pc_name,
cast(sum(case when (Numbers.Phone = 'CPU/' + PCName) then 1 else 0 end) as bit)
as cpu_contact,
cast(sum(case when (Numbers.Phone = 'PC/' + PCName) then 1 else 0 end)) as bit)
as pc_contact,
cast(sum(case when (Numbers.Phone = 'LOGIN/' + PCName) then 1 else 0 end) as bit)
as login_contact,
FROM
IPAddress
JOIN Numbers ON
('CPU/' + PCName = Numbers.Phone) OR ('PC/' + PCName = Numbers.Phone) OR
('LOGIN/' + PCName = Numbers.Phone)
WHERE
$where --Generated In code
GROUP BY
Status, Address, PCName

由于您在行之间进行逻辑或运算,因此总和为零为假,而任何大于 0 的值都为真。

关于sql - 如何在 SQL 中创建 bool 计算字段并加入该计算字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/417371/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com