带有子查询的SQL Pivot

时间:2017-12-18 18:20:22

标签: sql tsql pivot

我有一张看起来像这样的表

value | effective_date
----------------------
  'A' | '2000-10-31' 
  'A' | '2000-11-30'
  'B' | '2000-10-31'
  'B' | '2000-11-30'
  'C' | '2001-10-31'
  'C' | '2001-12-31'

如何透过effective_date列来显示每个日期是否存在值?

输出:

value | 2000-10-31 | 2000-11-30 | 2001-10-31 | 2001-12-31
  'A' |      1     |      1     |      0     |     0
  'B' |      1     |      1     |      0     |     0
  'C' |      0     |      0     |      1     |     1

我用

选择第一个表格
SELECT DISTINCT value, effective_date
FROM table
WHERE condition

effective_date

SELECT DISTINCT effective_date
FROM table
ORDER BY effective_date

1 个答案:

答案 0 :(得分:2)

extension String {
  init<B: FixedWidthInteger>(fullBinary value: B) {
    self = value.words.reduce(into: "") {
      $0.append(contentsOf: repeatElement("0", count: $1.leadingZeroBitCount))
      $0.append(String($1, radix: 2))
    }
  }
}