ここ結果より試験と次のコードの別のバージョンです。
DECLARE @testType TABLE(
TestID INT,
TestName varchar(128)
)
DECLARE @testRequest TABLE(
TestRequestID INT,
TestID INT,
TestCost INT,
TestDate DATETIME
)
INSERT INTO @testType (TestID,TestName) VALUES (1, 'Bone');
INSERT INTO @testType (TestID,TestName) VALUES (2, 'Chest');
-- These 2 test will no get a match and will be null
INSERT INTO @testType (TestID,TestName) VALUES (3, 'Head');
INSERT INTO @testType (TestID,TestName) VALUES (4, 'Infection');
INSERT INTO @testType (TestID,TestName) VALUES (5, 'Leg');
INSERT INTO @testRequest (TestRequestID, TestID, TestCost, TestDate) VALUES (1, 1, 10, GETDATE())
INSERT INTO @testRequest (TestRequestID, TestID, TestCost, TestDate) VALUES (2, 1, 10, GETDATE())
INSERT INTO @testRequest (TestRequestID, TestID, TestCost, TestDate) VALUES (3, 2, 20, GETDATE())
INSERT INTO @testRequest (TestRequestID, TestID, TestCost, TestDate) VALUES (4, 2, 20, GETDATE())
INSERT INTO @testRequest (TestRequestID, TestID, TestCost, TestDate) VALUES (4, 2, 20, GETDATE())
INSERT INTO @testRequest (TestRequestID, TestID, TestCost, TestDate) VALUES (4, 2, 20, GETDATE())
-- TestID 3 will get a 1 match here
INSERT INTO @testRequest (TestRequestID, TestID, TestCost, TestDate) VALUES (4, 3, 50, GETDATE())
-- TestID 3 will not get a match b/c of the date
INSERT INTO @testRequest (TestRequestID, TestID, TestCost, TestDate) VALUES (4, 3, 50, '2015-01-01')
-- TestID 4 will not get a match b/c of the date, null record
INSERT INTO @testRequest (TestRequestID, TestID, TestCost, TestDate) VALUES (4, 4, 100, '2018-01-01')
-- TestID 5 will not get a match b/c none one scheduled it yet, null record
SELECT
TT.TestName,
COUNT(TR.TestRequestID) [TestCount],
ISNULL(SUM(TR.TestCost),0) [TotalCost]
FROM @testType TT
LEFT JOIN @testRequest TR ON TT.TestID = TR.TestID
AND TR.TestDate BETWEEN GETDATE() AND GETDATE()
GROUP BY TT.TestName;
/*
Results:
Bone 2 20
Chest 4 80
Head 1 50
Infection 0 0
Leg 0 0
*/
-- To see null values run the query below
SELECT
*
FROM @testType TT
LEFT JOIN @testRequest TR ON TT.TestID = TR.TestID
AND TR.TestDate BETWEEN GETDATE() AND GETDATE()
/*
Results:
1 Bone 1 1 10 2017-01-16 20:17:31.030
1 Bone 2 1 10 2017-01-16 20:17:31.030
2 Chest 3 2 20 2017-01-16 20:17:31.030
2 Chest 4 2 20 2017-01-16 20:17:31.030
2 Chest 4 2 20 2017-01-16 20:17:31.030
2 Chest 4 2 20 2017-01-16 20:17:31.030
3 Head 4 3 50 2017-01-16 20:17:31.030
4 Infection NULL NULL NULL NULL
5 Leg NULL NULL NULL NULL
*/
代わりにLEFT JOINをTestRequestTestNameに追加する必要があるときに、日付制約をWHERE句として追加すると思いますか? LEFT JOINを持っているがWHERE句に条件を追加すると、OUTER JOININGになっているテーブルの値に応じて、INNER JOINが効果的に作成されます。 –
あなたの返信をありがとうScsimon.iはTestRequestTestNameとJoin節を残して試しましたが、要求されたテストのみが表示されていました。問題を解決しましたか、RequestDateがnullです。range.iがクエリを更新しました。ありがとう:) –