此查询
SELECT T.TestTypeId, F.FlockCode, AMT, CV, S.SampleDate
FROM [dbo].[Tests] AS T
JOIN [Samples] AS S ON T.SampleId = S.Id
JOIN [TestTypes] AS TT ON T.TestTypeId = TT.Id
JOIN [Flocks] AS F ON T.FlockId = F.Id
WHERE T.TestTypeId = 7 AND T.IsDeleted = 0
AND S.SampleDate BETWEEN '2017-12-17' AND '2018-01-08'
AND T.FlockId IN (7,13)
ORDER BY S.SampleDate, F.FlockCode
返回以下结果
TestTypeId FlockCode AMT CV SampleDate
7 R1.33 8.93 9.28 2017-12-17
7 R1.33 9.05 10.76 2018-01-01
7 R1.37 8.95 8.99 2018-01-01
对于现有数据是准确的,对于S.SampleDate
2017-12-17,FlockCode
R1.33只有一行。
现在我需要在2017-12-17数据FlockCode
R1.37的结果中添加另一行0
或null
AMT
& ; CV
值。TestTypeId FlockCode AMT CV SampleDate
7 R1.33 8.93 9.28 2017-12-17
7 R1.37 0 0 2017-12-17
7 R1.33 9.05 10.76 2018-01-01
7 R1.37 8.95 8.99 2018-01-01
所以预期的结果是
SQL
LINQ
或C#
或[DataContract]
public class LookupModelBase
{
[XmlAttribute, DataMember]
public int Id { get; set; }
[XmlText, DataMember]
public string Label { get; set; }
}
中的任何解决方案都会非常有用。提前谢谢。
答案 0 :(得分:3)
基本结构是使用cross join
和left join
执行此操作。你的查询有点复杂,所以我建议:
with t as (
SELECT T.TestTypeId, F.FlockCode, AMT, CV, S.SampleDate
FROM [dbo].[Tests] T JOIN
[Samples] S
ON T.SampleId = S.Id JOIN
[TestTypes] TT
ON T.TestTypeId = TT.Id JOIN
[Flocks] F
ON T.FlockId = F.Id
WHERE T.TestTypeId = 7 AND T.IsDeleted = 0 AND
S.SampleDate BETWEEN '2017-12-17' AND '2018-01-08' AND
T.FlockId IN (7, 13)
)
SELECT f.TestTypeId, f.FlockCode, COALESCE(t.AMT, 0) as AMT,
COALESCE(t.CV, 0) as CV, d.SampleDate
FROM (SELECT DISTINCT TestTypeId, FlockCode FROM t) f CROSS JOIN
(SELECT DISTINCT SampleDate FROM t) d LEFT JOIN
t
ON f.FlockCode = t.FlockCode AND f.TestTypeId = t.TestTypeId,
d.SampleDate = t.SampleDate
ORDER BY d.SampleDate, f.FlockCode;
答案 1 :(得分:0)
在 SQL 中,您可以使用UNION
运算符
SELECT T.TestTypeId, F.FlockCode, AMT, CV, S.SampleDate
FROM [dbo].[Tests] AS T
JOIN [Samples] AS S ON T.SampleId = S.Id
JOIN [TestTypes] AS TT ON T.TestTypeId = TT.Id
JOIN [Flocks] AS F ON T.FlockId = F.Id
WHERE T.TestTypeId = 7 AND T.IsDeleted = 0
AND S.SampleDate BETWEEN '2017-12-17' AND '2018-01-08'
AND T.FlockId IN (7,13)
UNION
SELECT 7 AS TestTypeId, 'R1.37' AS FlockCode, 0 AS AMT, 0 AS CV, '2017-12-17' AS SampleDate
ORDER BY SampleDate, FlockCode
答案 2 :(得分:0)
只是UNION
它!
SELECT T.TestTypeId, F.FlockCode, AMT, CV, S.SampleDate
FROM [dbo].[Tests] AS T
JOIN [Samples] AS S ON T.SampleId = S.Id
JOIN [TestTypes] AS TT ON T.TestTypeId = TT.Id
JOIN [Flocks] AS F ON T.FlockId = F.Id
WHERE T.TestTypeId = 7 AND T.IsDeleted = 0
AND S.SampleDate BETWEEN '2017-12-17' AND '2018-01-08'
AND T.FlockId IN (7,13)
UNION
SELECT 7 AS TestTypeId, 'R1.37' as FlockCode, 0 as AMT, 0 as CV, '2017-12-17' as SampleDate
ORDER BY SampleDate, FlockCode