几天前我开始学习 SQL,我有以下查询,它在“case”附近给了我一个错误,我似乎无法弄清楚:
SELECT * , Stuff((SELECT ', ' + CAST( orderid as varchar(10))
FROM( oitems t2
case when (ocardtype in ('PayPal','Sofort') OR
ocardtype in ('mastercard','visa') and
odate is not null) then
FOR XML PATH(''), 1, 2, '') [Proccessed] else FOR XML PATH(''), 1, 2, '') [NotProccessed] end)
FROM orders t1
Group by orderid,t1.odate, t1.ocardtype
我猜你知道这段代码应该做什么,但我不确定这是否是正确的使用方式select case
。
oitems table
+---------+-----------+----------+
| orderid | catalogid | numitems |
+---------+-----------+----------+
| o737 | 353 | 1 |
| o738 | 364 | 4 |
| o739 | 353 | 3 |
| o740 | 364 | 6 |
| o741 | 882 | 2 |
| o742 | 224 | 5 |
| o743 | 224 | 2 |
+---------+-----------+----------+
orders table
+-----------------+------------+------------+
| orderid | ocardtype | odate |
+-----------------+------------+------------+
| o737 | Paypal | | 'OK
| o738 | MasterCard | 01.02.2012 | 'OK
| o739 | MasterCard | 02.02.2012 | 'OK
| o740 | Visa | 03.02.2012 | 'OK
| o741 | Sofort | | 'OK
| o742 | | | 'ignore because ocardtype is empty
| o743 | MasterCard | | 'ignore because Mastercard no odate
+-----------------+------------+------------+
预期结果
+-----------+------------------------+--------------+
| catalogid | ProcessedSucssessfully | NotProcessed |
+-----------+------------------------+--------------+
| 353 |o737,o739 | |
| 364 |o738,o740 | |
| 882 |o741 | |
| 224 | |o742,o743 |
+-----------+------------------------+--------------+
我有以下条件,您可以在上述代码的案例陈述中找到这些条件
如果
ocardtype
为空,则添加orderid
到NotProcessed
如果
ocardtype
某些订单是万事达卡或维萨卡并且日期为空,则将 orderid 添加到NotProcessed
如果
ocardtype
是 Paypal 或 Sofort,则不要检查日期并将其添加orderid
到ProcessedSucssessfully