我有3张桌子:
Week
表Reference
表Inner
表但我对内表有些问题。
我想在内部表中添加一些与Final_table
相同的行
并为内部表中不存在的行添加0
我需要在SQL中进行查询才能完成。
请注意我有内部表格,我不是从tblWeek
和Reference
表创建的,但我可以使用它们
Week
01.08.2016
08.08.2016
16.08.2016
Final_table
Week RefNumber Value
RefNumber 01.08.16 100 15
100 01.08.16 200 3
200 01.08.16 300 0
300 08.08.16 100 8
08.08.16 200 0
08.08.16 300 0
16.08.16 100 0
16.08.16 200 0
16.08.16 300 7
Full_tbl
Week RefNumber Value
01.08.16 100 15
01.08.16 200 3
08.08.16 100 8
16.08.16 200 7
答案 0 :(得分:1)
您可以使用Right Join
和Cross Join
SELECT X.WEEK,X.RefNumber,ISNULL(T.Value,0) AS Value
FROM [Full_Tbl] T
RIGHT JOIN
(SELECT WEEK,RefNumber
FROM [WEEK]
CROSS JOIN [RefNumber] ) X
ON X.[WEEK]=T.[Week] AND X.[RefNumber] = T.[RefNumber]
ORDER BY X.[WEEK]
答案 1 :(得分:0)
我希望我的问题正确(主要来自附图)。
在这里,这应该有效:
SELECT f.week, f.refnumber, (CASE WHEN f.value IS NULL THEN 0 ELSE f.value END) as value
FROM Full_tbl f
RIGHT JOIN refnumber on f.refnumber = refnumber.refnumber
基本上我们做的是:
我们从“refnumber”表中获取所有行(即RIGHT JOIN)。
如果与此重新编号相关联的值为NUL1,则使用大小写为0。
答案 2 :(得分:0)
我们可union all
cross join
使用where not exists()
获取Week
和RefNumber
中inner_table
和select [Week], RefNumber, [Value]
from inner_table
union all
select [Week], RefNumber, [Value]=0
from [Week] w
cross join RefNumber r
where not exists (
select 1
from inner_table as i
where i.[Week] = w.[Week]
and i.RefNumber = r.RefNumber
)
的组合SELECT * FROM orders
JOIN products ON orders.productid = products.productid
ORDER BY userid
SELECT * FROM orders
JOIN products ON orders.productid = products.productid
WHERE userid = 555