2017-03-01 101 views
0

返回超過1行我有兩個表(卡貼)和(Rental_SimCard)內連接從第二臺

simcard的只包含像ID,PHONENUMBER,simcardnumber的卡貼的信息。

Rental_SimCard將有創紀錄的增加,每卡貼租賃

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 

我想顯示其有MAX DateOut唯一即使DateOut爲NULL

我目前使用的代碼卡貼的記錄由每列

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子句中。

現在我的查詢從卡貼表返回副本在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 - ... 

回答

1

您也可以使用CROSS APPLY

SELECT * 
FROM SimCard S 
CROSS APPLY (SELECT TOP 1 * 
      FROM Rental_SimCard R 
      WHERE R.SimCardId=S.SimCardId 
      ORDER BY DateOut DESC) T 
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 
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) 
1

只是讓內部聯接和GROUP BY 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