[英]How do I make a boolean calculated field in TSQL and join on that calculated field?
首先看看這段代碼。 我覺得它應該適合我,但事實並非如此! (驚喜!)
無論如何,這是我首先嘗試的:
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)
所以我想要的是一些布爾計算字段並在類似條件下加入。 我還希望結果可以折疊成單行。 例如,我認為當前的設置會做這樣的事情:
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 BY
和SUM
來折疊行:
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
由於您正在執行邏輯或行之間,因此零之和為false,而大於0的任何值都為true。
您需要使用Case / When進行比較。 在這種情況下,我硬編碼1或0,但T-SQL會將硬編碼的數字轉換為int。 如果你想要布爾(位),你需要手動轉換,就像這樣......
Convert(Bit, Case When Numbers.Phone = 'CPU/' + PCName Then 1 Else 0 End) as cpu_contact,
Convert(Bit, Case When Numbers.Phone = 'PC/' + PCName Then 1 Else 0 End) as pc_contact,
Convert(Bit, Case When Numbers.Phone = 'LOGIN/' + PCName Then 1 Else 0 End) as login_contact,
SELECT
Status as status,
Address as ip,
PCName as pc_name,
case when sum(case when Numbers.Phone = 'CPU/' + PCName then 1 end) > 0 then 'true' else 'false' end as cpu_contact,
case when sum(case when Numbers.Phone = 'PC/' + PCName then 1 end) > 0 then 'true' else 'false' end as pc_contact,
case when sum(case when Numbers.Phone = 'LOGIN/' + PCName then 1 end) > 0 then 'true' else 'false' end as login_contact
FROM IPAddress
JOIN Numbers
ON ('CPU/' + PCName = Numbers.Phone)
OR ('PC/' + PCName = Numbers.Phone)
OR ('LOGIN/' + PCName = Numbers.Phone)
WHERE -- your condition goes here
group by status, address, pc_name
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.