我有一个问题,我试图从一个表中返回所有行,同时用另一个表填充数据空白(如果它存在)。目前我有工作SQL,这是一个简单的例子来展示我在做什么。
SELECT a.timestamp,
number
FROM tablea a WITH (nolock)
UNION
SELECT b.timestamp,
number
FROM tablea a WITH (nolock)
RIGHT JOIN tableb b WITH (nolock)
ON a.timestamp = b.timestamp
WHERE a.timestamp IS NULL
通过一些示例数据,这会产生这个结果,这就是我想要的。 (抱歉格式化)
| TableA | | TableB | | Result |
| 2017-7-24 | 1 | | 2017-7-24 | 2 | | 2017-7-24 | 1 |
| 2017-7-26 | 2 | | 2017-7-25 | 3 | | 2017-7-25 | 3 |
| 2017-7-27 | 2 | | 2017-7-27 | 6 | | 2017-7-26 | 2 |
| 2017-7-27 | 2 |
这样就可以了,我只是想知道是否有不同的方法可以产生预期的结果?
答案 0 :(得分:1)
SELECT * FROM TAbleA
UNION ALL
SELECT * FROM TableB b
WHERE NOT EXISTS (
SELECT * FROM TableA a
WHERE a.timestamp = b.timestamp
SELECT * FROM TableA
UNION ALL
SELECT * FROM TableB
WHERE timestamp NOT IN (
SELECT timestamp FROM TableA
)
答案 1 :(得分:1)
<tbody>
<!-- ngRepeat: lineItem in paymentDetails.responseObject[0].schedules[0].schedule_line_items track by $index -->
<tr class="ng-scope" ng-repeat="lineItem in paymentDetails.responseObject[0].schedules[0].schedule_line_items track by $index">
<td class="ng-binding">Jul 27, 2017</td>
<td>
<td class="ng-binding">$45.00</td>
<!-- ngIf: paymentDetails.responseObject[0].fee_amount > 0 -->
<td class="ng-binding ng-scope" ng-if="paymentDetails.responseObject[0].fee_amount > 0">$0.90</td>
<!-- end ngIf: paymentDetails.responseObject[0].fee_amount > 0 -->
<td>
<td class="" ng-switch="" on="lineItem.statusString" ng-show="lineItem.statusString" style="">
<td class="ng-binding ng-hide" ng-show="!lineItem.statusString" ng-bind-html="receiptTemplate.ready" style="">Ready</td>
<td class="ng-binding" ng-show="lineItem.authorizationString" ng-bind-html="lineItem.authorizationString" style="">53433 Bogus Gateway: Forced success</td>
<td class="ng-hide" ng-show="!lineItem.authorizationString" style=""/>
<td>
</tr>
结果将为您提供更清晰(可能更有效)的查询:
coalesce
答案 2 :(得分:0)
SELECT * FROM TableA
UNION
SELECT * FROM TableB
WHERE timestamp NOT IN (SELECT timestamp FROM TableA)