简体   繁体   中英

How to repeat rows based on different columns in SQL Server

I have table with columns Monday , Tuesday , Wednesday , Thursday and Friday and are of Boolean type now I want to make a query to convert these rows to single column Weekday . It Should show me name of day of which column is true.

Note: I think you mean bit type instead of Boolean that accepts only 0 / 1 .

A mathematical way can be this:

select 
    datename(weekday,
       Monday + Tuesday*2 + Wednesday*3 + Thursday*4 + Friday*5 - 1) as weekDayName
from 
    t;

[ SQL Fiddle Demo ]

Side Note:

 datename(weekday, 0) => Monday datename(weekday, 1) => Tuesday datename(weekday, 2) => Wednesday datename(weekday, 3) => Thursday datename(weekday, 4) => Friday datename(weekday, 5) => Saturday datename(weekday, 6) => Sunday / datename(weekday, -1) => Sunday 

You can use case . To get a comma-delimited list in SQL Server:

select t.*,
       stuff( ((case when Monday <> 0 then ',Monday' else '' end) +
               (case when Tuesday <> 0 then ',Tuesday' else '' end) +
               . . .
              ), 1, 1, ''
            ) as weekdays
from t;

I don't know how you specify "true" values. The above assumes that non-zero values are true.

As pointed out, SQL Server does not have a boolean type, but it does have a BIT type which can only take on two values, 0 and 1. I am assuming that you are using a bit column. I also assume that only one day will be selected in each row. With both of these assumptions, you just need a single CASE expression:

SELECT
    CASE WHEN Monday = 1    THEN 'Monday'
         WHEN Tuesday = 1   THEN 'Tuesday'
         WHEN Wednesday = 1 THEN 'Wednesday'
         WHEN Thursday = 1  THEN 'Thursday'
         WHEN Friday = 1    THEN 'Friday' END AS day_selected
FROM yourTable

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