我想根据以下列获取输出。 让我知道我应该如何实现它。
我必须在where子句中将类别与merchantcategory
进行比较。
Table A, `Category` (with example data):
Travel | Gas | Restaurant | Spending
-------------------------------------------------------
All Other Merchants | gas | Hotel | Credit Card
U.S. Post Exchange | gas | Motel | Bill Payment
Table B, `MerchantCategory` columns:
College/School Expense
Hospital
Gas
Pre-Authorized Mail/Telephone Order
Hotel/Motel
Shopping
Credit Card Bill Payment
Grossary
All Other Merchants/U.S. Post Exchange
Restaurant
那么我应该如何通过将单独的列添加为id来实现它呢?
或者通过案例或其他方式使用?
答案 0 :(得分:0)
在每个类别值之间创建一个链接,可能在临时表中。
IF OBJECT_ID('tempdb..#CategoryConversions') IS NOT NULL
DROP TABLE #CategoryConversions
CREATE TABLE #CategoryConversions (
MerchantCategory VARCHAR(100),
Category VARCHAR(100))
INSERT INTO #CategoryConversions (
MerchantCategory,
Category)
VALUES
('gas', 'gas'),
('Spending', 'Grossary '),
('Spending', 'Credit Card Bill Payment'),
('Restaurant', 'Hotel/Motel')
--.....
现在加入所有3个:
SELECT
YourWantedColumns
FROM
TableA AS A
INNER JOIN #CategoryConversions AS C ON A.Category = C.Category
INNER JOIN TableB AS B ON C.MerchantCategory = B.MerchantCategory
如果您想避开临时表,可以使用以下方法:
;WITH CategoryConversions AS
(
SELECT
C.MerchantCategory,
C.Category
FROM
(VALUES
('gas', 'gas'),
('Spending', 'Grossary '),
('Spending', 'Credit Card Bill Payment'),
('Restaurant', 'Hotel/Motel')
--......
) AS C(MerchantCategory, Category)
)
SELECT
YourWantedColumns
FROM
TableA AS A
INNER JOIN CategoryConversions AS C ON A.Category = C.Category
INNER JOIN TableB AS B ON C.MerchantCategory = B.MerchantCategory