使用与其他表的水平关系从两个表中选择多个值

时间:2015-07-23 16:05:32

标签: sql sql-server sql-server-2008

所有专家

请原谅我这个主题我无法找出解释这个场景的任何其他东西。

我正在使用一个有很多糟糕的数据库问题的旧数据库。

表格结构

表:品牌

ID 名称 muId(LpMap表LpID和其余四个相同) 中 妇女参与发展 出价 GID

表:LpMap LPID 名称 Asscoiate Id(来自LpMapConfig的fk)

表:LpMapConfig> ID LPID  dateCreated会

数据发布图片以表格显示数据 enter image description here

enter image description here

期望的输出 enter image description here

所以我想做的是 - 编写一个sql查询,获取Id,名称和计数(Mid,MEid,Gid,Wid Bid)如果所有五个都有值,则count将为5,其中任何一个为null那么它将是4。

1 个答案:

答案 0 :(得分:1)

select name, id,
case when mid is not null then 1 else 0 +
case when meid is not null then 1 else 0 +
case when gid is not null then 1 else 0 +
case when wid is not null then 1 else 0 +
case when bid is not null then 1 else 0 
end as count
from BRAND