我有两个表Orderline和InvoiceLine。我需要根据orderid和orderitemkey
在一行中显示数据表:订单行
+---------+--------------+--------+
| OrderId | OrderItemKey | Amount |
+---------+--------------+--------+
| 410 | 10 | 25 |
| 410 | 20 | 50 |
+---------+--------------+--------+
表:InvoiceLine
+-----------+-------------+------------+---------+-------------+
| Invoiceid | Description | InvoiceAmt | OrderId | OrderItemKey |
+-----------+-------------+------------+---------+-------------+
| 1 | xxxx | 10 | 10 | 410 |
| 2 | bbb | 15 | 10 | 410 |
| 3 | ccccc | 50 | 20 | 410 |
+-----------+-------------+------------+---------+-------------+
WITH ORDERLINE AS
SELECT orderid,
orderitemkey,
amount
FROM tbl_orderline ), invoiceline AS
(
SELECT invoiceid,
max(description),
sum(invoiceamt),
orderid,
orderitemkey
FROM tbl_invoiceline
GROUP BY invoiceid,
orderid,
orderitemkey )SELECT O.ORDERID,
O.ORDERITEMKEY,
O.AMOUNT,
I.invoiceid,
I.description,
I.invoiceamt
FROM TBL_ORDERLINE O
LEFT JOIN TBL_INVOICELINE
ON O.ORDERID = I.orderid
AND O.ORDERITEMKEY = I.orderitemkey
数据应显示如下:
+---------+--------------+--------+-----------+-------------+------------+
| OrderId | OrderItemKey | Amount | InvoiceID | Description | InvoiceAmt |
+---------+--------------+--------+-----------+-------------+------------+
| 410 | 10 | 25 | 1 | xxxx | 10 |
| | | | 2 | bbb | 15 |
| 410 | 20 | 50 | 3 | ccccc | 50 |
+---------+--------------+--------+-----------+-------------+------------+
但它显示如下:
+---------+--------------+--------+-----------+-------------+------------+
| OrderId | OrderItemKey | Amount | InvoiceID | Description | InvoiceAmt |
+---------+--------------+--------+-----------+-------------+------------+
| 410 | 10 | 25 | 1 | xxxx | 10 |
| 410 | 140 | 25 | 2 | bbb | 15 |
| 410 | 20 | 50 | 3 | ccccc | 50 |
+---------+--------------+--------+-----------+-------------+------------+
请帮忙吗?
我正在使用MS SQL。 对于orderitemkey,这是一个错误,它显示10。
+---------+--------------+--------+-----------+-------------+------------+
| OrderId | OrderItemKey | Amount | InvoiceID | Description | InvoiceAmt |
+---------+--------------+--------+-----------+-------------+------------+
| 10 | 410 | 25 | 1 | xxxx | 10 |
| 10 | 410 | 25 | 2 | bbb | 15 |
| 20 | 410 | 50 | 3 | ccccc | 50 |
+---------+--------------+--------+-----------+-------------+------------+
答案 0 :(得分:0)
数据看起来好了(InvoiceLine中有3行,输出中有3行)。
如果您只想使用SSRS进行漂亮的格式化,则需要use tablix groupings。
如果您确实需要以您想要的格式从SQL返回数据,则需要重新考虑连接 - 因为您只希望将分组的ORDERLINE
连接到{{的第一行1}},您需要实际number the rows in invoiceline using window functions - 类似于INVOICELINE
,然后加入ROW_NUMBER() OVER(ORDER BY invoiceid, orderid, orderitemkey PARTITIONBY orderid, orderitemkey) AS RowNumber
。