简体   繁体   中英

select different values from same column in a table and display it under different columns

I have a table named "ORDER_HISTORY" where there is a column named "Status".The "Status" column contains different status values for different stores.

My requirement is that I need to fetch the different status values(count) for each store and display these in their corresponding columns.For example: If i have 53(order_cancelled) and 57(order_completed) as two status, and for store number 20 I have two orders with status 57(ieorder_completed) and one order with status 53(order_cancelled),then i need to display the result(count) in the format as below as:

================================================
Store_ID || order_cancelled || order_completed||
------------------------------------------------
20       || 1               || 2              ||
================================================    

How to write a query that does the above work?

Please help.Thanks in advance!!

try this

SELECT a.Store_ID,b.total as order_completed,c.total as order_completed FROM ORDER_HISTORY a
LEFT OUTER join (select Store_ID,count(*) as total from ORDER_HISTORY where Status=57 group by Store_ID) b on a.Store_ID=b.Store_ID
LEFT OUTER join (select Store_ID,count(*) as total from ORDER_HISTORY where Status=53 group by Store_ID) c on a.Store_ID=c.Store_ID
group by a.Store_ID

try this

SELECT Store_ID, (SELECT COUNT(Status) FROM order_history WHERE Status = 53) AS order_cancelled, (select COUNT(Status) FROM order_history WHERE Status = 57) order_completed FROM clover_source.order_history group by Store_ID ;

try this:

SELECT dbo.ORDER_HISTORY.Store_ID, ORDER_HISTORY_Cancelled.order_cancelled, ORDER_HISTORY_completed.order_completed FROM dbo.ORDER_HISTORY LEFT OUTER JOIN (SELECT Store_ID, COUNT(Status) AS order_cancelled FROM dbo.ORDER_HISTORY AS TotalCancelled WHERE (Status = N'53') GROUP BY Store_ID) AS ORDER_HISTORY_Cancelled ON dbo.ORDER_HISTORY.Store_ID = ORDER_HISTORY_Cancelled.Store_ID LEFT OUTER JOIN (SELECT Store_ID, COUNT(Status) AS order_completed FROM dbo.ORDER_HISTORY AS TotalComleted WHERE (Status = N'57') GROUP BY Store_ID) AS ORDER_HISTORY_completed ON dbo.ORDER_HISTORY.Store_ID = ORDER_HISTORY_completed.Store_ID GROUP BY dbo.ORDER_HISTORY.Store_ID, ORDER_HISTORY_Cancelled.order_cancelled, ORDER_HISTORY_completed.order_completed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM