如何根据SQL Server中的不同列重复行

时间:2017-09-05 11:58:47

标签: sql sql-server tsql weekday

我的表格包含MondayTuesdayWednesdayThursdayFriday列,现在属于布尔类型我想进行查询以将这些行转换为单列Weekday。它应该显示哪一天的名字哪个列是真的。

3 个答案:

答案 0 :(得分:2)

  

注意:我认为您的意思是bit类型而非Boolean仅接受0 / 1

数学方法可以是这样的:

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

[ SQL Fiddle Demo ]

  

旁注:

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

答案 1 :(得分:0)

您可以使用case。在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;

我不知道你如何指定“真实”值。以上假设非零值为真。

答案 2 :(得分:0)

正如所指出的,SQL Server没有布尔类型,但它确实有一个BIT类型,它只能接受两个值,0和1.我假设您使用的是一个位列。我还假设每行只选择一天。有了这两个假设,你只需要一个CASE表达式:

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