Select rows with same value and then insert a null record
i have written an query but it inserts alternate null columns. I want the null column after different orderids. Suppose i have two orderids 100 and 101. i have only one record for orderid 100 and two records for orderid 101 so it should insert null column after orderid 100 and then after 101 orderid.
DECLARE @tmp TABLE
(
srno int identity (1,1) ,
orderid int,
orderdate datetime,
orderstatus varchar(255),
product_name varchar(255),
shipping_cost decimal(18,2),
Quantity int,
TotalPrice money,
SalesTax1 money,
CVV2_Response varchar(255),
ShipFirstName varchar(255),
ShipLastName varchar(255),
ShipAddress1 varchar(255),
ShipCity varchar(255),
ShipState varchar(255),
ShipPostalCode varchar(255),
EmailAddress varchar(255),
CustomerID int
)
SELECT CASE D.N WHEN 1 THEN ord.orderid end as orderid,CASE D.N WHEN 1 THEN ord.orderdate end as orderdate,
CASE D.N WHEN 1 THEN ord.OrderStatus end as Orderstatus,
CASE D.N WHEN 1 THEN ord.productname end as Productname,
CASE D.N WHEN 1 THEN ord.Quantity end as Quantity,
CASE D.N WHEN 1 THEN ord.TotalPrice end AS PaymentAmount,
CASE D.N WHEN 1 THEN ord.SalesTax1 ELSE 0.0 END AS Tax ,
CASE WHEN row_no = 1 THEN ord.totalshippingcost ELSE 0.0 END AS Totalshippingcost,
CASE D.N WHEN 1 THEN ord.CVV2_Response end as CVV2_Response ,
CASE D.N WHEN 1 THEN ord.ShipFirstNam开发者_开发技巧e end as ShipFirstName ,
CASE D.N WHEN 1 THEN ord.ShipLastName end as ShipLastName ,
CASE D.N WHEN 1 THEN ord.ShipAddress1 end as ShipAddress1 ,
CASE D.N WHEN 1 THEN ord.ShipCity end as ShipCity ,
CASE D.N WHEN 1 THEN ord.ShipState end as ShipState ,
CASE D.N WHEN 1 THEN ord.ShipPostalCode end as ShipPostalCode,
CASE D.N WHEN 1 THEN ord.EmailAddress end AS CustomerEmail
FROM
(
SELECT ROW_NUMBER() OVER(PARTITION BY ord.orderid ORDER BY ord.orderid, ord.orderdate, ord.OrderStatus, odn.productname, odn.Quantity, odn.TotalPrice,ord.SalesTax1,ord.totalshippingcost,ord.CVV2_Response ,ord.ShipFirstName ,ord.ShipLastName ,
ord.ShipAddress1 ,ord.ShipCity ,ord.ShipState ,ord.ShipPostalCode ,cus.EmailAddress) AS row_no, ord.orderid,
ord.orderdate, ord.OrderStatus, odn.productname, odn.Quantity, odn.TotalPrice,ord.SalesTax1,ord.totalshippingcost,ord.CVV2_Response ,ord.ShipFirstName ,ord.ShipLastName ,
ord.ShipAddress1 ,ord.ShipCity ,ord.ShipState ,ord.ShipPostalCode ,cus.EmailAddress
FROM Orders AS ord
INNER JOIN orderdetails AS odn ON odn.orderid = ord.orderid INNER Join Customers AS cus on ord.CustomerID = cus.CustomerID WHERE ord.OrderStatus = 'Processing'
) ord
CROSS JOIN (SELECT 1 UNION ALL SELECT 2) AS D(N)
ORDER BY ord.orderid, ord.orderdate, ord.productname, D.N
Try this as order by:
order by row_number() over(order by ord.orderid, ord.orderdate, ord.productname)
精彩评论