表1
Color, Total
------------
Red,5
Blue,3
Pink,1
表2
Color, Total
------------
Red,3
Blue,2
Pink,1
期望的结果是:
Results
Color, Total
------------
Red,2
Blue,1
Pink,0
如何从table1中的总列中减去table2中的总列数?
答案 0 :(得分:4)
您需要连接表格并减去值:
SELECT t1.color, t1.total - t2.total as Total
FROM @Table1 t1 INNER JOIN @Table2 t2
ON t1.color = t2.color
此处已更新SQL Fiddle
答案 1 :(得分:3)
使用JOIN
DECLARE @Table1 Table (color nvarchar(4), total int)
INSERT INTO @Table1 Values ('Red', 5)
INSERT INTO @Table1 Values ('Blue', 2)
INSERT INTO @Table1 Values ('Pink', 1)
DECLARE @Table2 Table (color nvarchar(4), total int)
INSERT INTO @Table2 Values ('Red', 3)
INSERT INTO @Table2 Values ('Blue', 1)
INSERT INTO @Table2 Values ('Pink', 1)
SELECT t1.color,t1.total - t2.total as total
from @Table1 t1
join @Table2 t2
on t1.color = t2.color;
答案 2 :(得分:2)
JOIN
是不错的选择,但我们认为不同:
<强> SqlFiddle 强>
SELECT t.color, SUM(t.total) as total
FROM (
select color, total from @Table1
UNION ALL
select color, -total from @Table2) AS t
GROUP BY t.color
ORDER BY total DESC