内连接从第二个表返回多于1行

时间:2017-03-01 09:38:24

标签: c# sql-server

我有两张桌子(SimCard)和(Rental_SimCard)

Simcard只包含sim卡的信息,如id,phonenumber,simcardnumber。

Rental_SimCard将为每次SIM卡租用添加一条记录

Rental_SimCard - SimCardID - DateOut  - DateIn
 0              - 1         - 1/3/2017 - 1/4/2017
 1              - 1         - 1/5/2017 - 1/6/2017
 2              - 1         - 1/7/2017 - NULL
 3              - 2         - 1/7/2017 - NULL
 4              - 3         - NULL     - NULL

我想显示即使DateOut为NULL也只有MAX DateOut的simcard记录

我目前正在使用的代码

    string sqlquery = "Select *, " +
        "CASE WHEN MAX(CASE WHEN DateOut IS NULL THEN 1 ELSE 0 END) = 0 THEN " +
        "MAX(DateOut) END AS MaxDateOut FROM SimCard INNER JOIN Rental_SimCard ON Rental_SimCard.SimCardID=SimCard.SimCardID " +
        "GROUP BY (Every Single Column In the two tables)

我按每列分组,因为我一直收到此错误

  

列'SimCard.SimCardID'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

现在我的查询从simcard表返回Rental_SimCard中重新创建的每条记录的副本

我想要的结果应该是

Rental_SimCard - SimCardID - DateOut(MAX)  - DateIn - SimCardRecords...
 2              - 1         - 1/7/2017      - NULL   - ...
 3              - 2         - 1/7/2017      - NULL   - ...
 4              - 3         - NULL          - NULL   - ...

4 个答案:

答案 0 :(得分:3)

SELECT MAX(Rental_SimCard)
    ,SimCard.SimCardId
    ,MAX(DATEOut)
    ,MAX(DateIn)
    ,MAX(SimCardRecords)
FROM SimCard
INNER JOIN RENTAL_SIMCARD ON SimCard.SimCardId = Rental_SimCard.SimCardID
GROUP BY SimCard.SimaCardId

答案 1 :(得分:1)

您也可以使用[Test] public void Index_HasParamWithBinderAttribute() { var targetType = typeof(DefaultController); var targetAction = targetType.GetMethod("Index", BindingFlags.Instance | BindingFlags.Public); // if there is an exception below, someone removed action from the controller var targetParams = targetAction.GetParameters().FirstOrDefault(x => x.Name == "MyId"); // if there is an exception below, then someone renamed the action argument Assert.That(targetParams.ParameterType, Is.EqualTo(typeof(int?))); // if this fails, then someone changed the type of parameter Assert.That((targetParams.GetCustomAttributes(true).FirstOrDefault() as ModelBinderAttribute).BinderType, Is.EqualTo(typeof(MyBinder))); // if this fails, then either there is no more a modelbinder or the type is wrong }

CROSS APPLY

答案 2 :(得分:1)

简单地通过SimCardId进行内部加入和分组

SELECT s.SimCardId
    ,max(Rental_SimCard)
    ,max(DATEOut)
    ,max(DateIn)
    ,max(SimCardRecords)
FROM SimCard s
INNER JOIN RENTAL_SIMCARD rs ON s.SimCardId = rs.SimCardID
GROUP BY s.SimCardId

答案 3 :(得分:0)

检查

select * from Rental_SimCard r inner join SimCard s
on s.SimCardID=r.SimCardID 
where 
( DateOut = (select max(DateOut) from Rental_SimCard)
or DateOut is null )