在下表中,根据说明,我们在不同的列中有不同的数量。我们希望使用T-SQL脚本将所有数量放在一列中,而将desc放在另一列中。表名是rawdata。
当前表格结果:
SSI_CUST_TRANS# WAYBILL# BILL_OF_LADING NET_FREIGHT_CHARGES MISC_CODE1_DESC MISC_CODE1_AMT MISC_CODE2_DESC MISC_CODE2_AMT MISC_CODE3_DESC MISC_CODE3_AMT MISC_CODE4_DESC MISC_CODE4_AMT
3574296 618852 618852 32.5 SPECIAL DELIVERY 40 FUEL SURCHARGE 4.88 NULL NULL NULL NULL
3574319 618852 618852 32.5 SPECIAL DELIVERY 40 FUEL SURCHARGE 4.88 NULL NULL NULL NULL
必填结果:
BILL_OF_LADING WAYBILL# SSI_CUST_TRANS# Charge Type Desc Amount
618852 618852 3574296 AMOUNT_PAID 77.38
618852 618852 3574296 NET_FREIGHT_CHARGES ELECTRONIC EQUIP./PARTS 32.5
618852 618852 3574296 SPECIAL DELIVERY 40
618852 618852 3574296 FUEL SURCHARGE 4.88
618852 618852 3574319 AMOUNT_PAID 0
618852 618852 3574319 NET_FREIGHT_CHARGES ELECTRONIC EQUIP./PARTS 32.5
618852 618852 3574319 SPECIAL DELIVERY 40
618852 618852 3574319 FUEL SURCHARGE 4.88
我们希望数量和描述如图所示进行转置。
答案 0 :(得分:1)
从上面的数据尝试这样的 预期输出需要更多数据
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="one_to_many">click
<form action="demo_form.asp">
<input type="checkbox" name="graph" value="like"> کامنت ها<br>
<input type="checkbox" name="graph" value="comment" checked> لایک ها<br>
<input type="checkbox" name="graph" value="friend" checked> دوستان<br>
<input type="button" id="cls_btn" value="رسم گراف">
</form>
</div>
输出
CREATE TABLE #A
(
SSI_CUST_TRANS BIGINT,
WAYBILL BIGINT,
BILL_OF_LADING BIGINT,
NET_FREIGHT_CHARGES NUMERIC(22,6),
MISC_CODE1_DESC VARCHAR(100),
MISC_CODE1_AMT BIGINT,
MISC_CODE2_DESC VARCHAR(100),
MISC_CODE2_AMT BIGINT,
MISC_CODE3_DESC VARCHAR(100),
MISC_CODE3_AMT BIGINT,
MISC_CODE4_DESC VARCHAR(100),
MISC_CODE4_AMT BIGINT
)
INSERT INTO #A
(SSI_CUST_TRANS,WAYBILL,BILL_OF_LADING,NET_FREIGHT_CHARGES,MISC_CODE1_DESC,MISC_CODE1_AMT,MISC_CODE2_DESC,MISC_CODE2_AMT)
VALUES
(3574296,618852,618852,32.5,'SPECIAL DELIVERY',40,'FUEL SURCHARGE',4.88),
(3574319,618852,618852,32.5,'SPECIAL DELIVERY',40,'FUEL SURCHARGE',4.88)
SELECT DISTINCT BILL_OF_LADING,WAYBILL,SSI_CUST_TRANS,CHARGE_TYPE,NET_FREIGHT_CHARGES,AMOUNT
FROM #A
CROSS APPLY (VALUES (MISC_CODE1_DESC, MISC_CODE1_AMT),
(MISC_CODE2_DESC, MISC_CODE2_AMT),
(MISC_CODE3_DESC, MISC_CODE3_AMT),
(MISC_CODE4_DESC, MISC_CODE4_AMT)
)
CROSSAPPLIED (CHARGE_TYPE, AMOUNT)