1

我有 5 张桌子

Village

在此处输入图像描述


 T1_Master (Village_ID is a foreign key)

在此处输入图像描述


T2_Master (Village_ID is a foreign key)

在此处输入图像描述


T1_Details (t1_id is a foreign key) & (month,year,t1_id are combination of primary key(复合键))

在此处输入图像描述


T2_Details (t2_id is a foreign key) & (month,year,t2_id are combination of primary key(复合键)) 在此处输入图像描述

现在,如果我想检索记录在哪里village_ID = 01, month=03 and year=2013

那么输出应该如下

在此处输入图像描述

here t1_1(No) = t1_1 has no record for month=03 and year=2013

Like wise t2_1(Yes) = t2_1 has record for month=03 and year=2013等等...

请帮帮我....请

4

2 回答 2

0

您将需要使用外连接来获取空值(您可能需要考虑在左连接上查找一些可用的教程 - 很多都在 google 上)。关键是在详细信息行不可用时使用主表显示 id。

SELECT  v.Village_id, 
        CASE WHEN t1d.t1_id IS NULL THEN CAST(t1m.t1_id AS VARCHAR(50)) + ' (No)'
                ELSE CAST(t1m.t1_id AS VARCHAR(50)) + ' (Yes)'
        END T1,
        CASE WHEN t2d.t2_id IS NULL THEN CAST(t2m.t2_id AS VARCHAR(50)) + ' (No)'
                ELSE CAST(t2m.t2_id AS VARCHAR(50)) + ' (Yes)'
        END T2
FROM Village v 
        LEFT OUTER JOIN T1_Master t1m
        ON t1m.Village_ID = v.Village_ID
        LEFT OUTER JOIN T1_Details t1d
        ON t1d.t1_id = t1m.t1_id
            AND t1d.[month] = 03
            AND t1d.[year] = 2013
        LEFT OUTER JOIN T2_Master t2m
        ON t2m.Village_ID = v.Village_ID
        LEFT OUTER JOIN T2_Details t2d
        ON t2d.t2_id = t2m.t2_id
            AND t2d.[month] = 03
            AND t2d.[year] = 2013
WHERE v.Village_ID = 01

根据您在数据库上的空值设置,该CAST(t2m.t2_id AS VARCHAR(50)) + ' (No)'语句可能需要检查 t2m 记录是否为空,以使其显示空值而不是仅显示“(否)”

于 2013-05-30T16:06:08.527 回答
0

我认为您想隐含一个或多个 LEFT 或 RIGHT JOIN (s):

 SELECT
    V.Village_ID    
    , Dates.[MONTH]
    , Dates.[YEAR]
    , CASE WHEN colValue IS NULL THEN 'no'
         ELSE 'yes'
         END [Yes or No]
FROM
    (
    SELECT
       Village_ID
    FROM 
        Villages
    WHERE
        Village_ID = @ParamVilageID
    ) V
    LEFT JOIN
    (
    SELECT
        Viilage_ID
        , [MONTH]
        , [YEAR]
    FROM
        T1_Details
    WHERE
        [MONTH] = @ParamMonth
        AND
        [YEAR] = @ParamYear
    ) Dates
    ON V.Village_ID = Dates.Village_ID

您需要决定将哪个列引用为 colValue,但所有 SQL 元素都在那里。SQL 将从 tha case 语句推断数据类型(字符串),但您也可以返回直接布尔值 0 或 1

顺便说一句,最好有一个 smallDate 列,因为 SQL 有 DatePart 和 DateName 函数

于 2013-05-30T15:19:08.087 回答