我有以下查询:
SELECT
CAST(t. NAME AS CHAR(12)) AS [ TABLE ],
CAST(c. NAME AS CHAR(20)) AS [ COLUMN ],
CAST(d. NAME AS CHAR(9)) AS [ DATA type ],
CASE WHEN d. NAME IN ('char', 'varchar') THEN
STR (c.max_length, 6, 0)
ELSE
''
END AS [ Length ],
CASE WHEN d. NAME IN ('numeric', 'decimal') THEN
STR (c. PRECISION, 9, 0)
ELSE
''
END AS [ PRECISION ],
CASE WHEN d. NAME IN ('numeric', 'decimal') THEN
STR (c.scale, 5, 0)
ELSE
''
END AS [ Scale ],
CASE c.is_nullable
WHEN 0 THEN
'not null'
ELSE
''
END AS [ Nullable ]
FROM
sys. COLUMNS AS c
JOIN sys. TABLES AS t ON c.object_id = t.object_id
JOIN sys.types AS d ON c.system_type_id = d.system_type_id
ORDER BY
1,
column_id;
这给了我这样的东西:
Table | Column | Data type|
__________________________________
Customer| CustomerCode| int |
Customer| LastName | varchar |
Customer| FirstName | varchar |
Customer| AreaCode | char |
Employee| Title | char |
Employee| LastName | varchar |
Employee| FirstName | varchar |
但是,我想在表格中只显示一次重复的单词,如下所示:
Table | Column | Data type|
__________________________________
Customer| CustomerCode| int |
| LastName | varchar |
| FirstName | varchar |
| AreaCode | char |
Employee| Title | char |
| LastName | varchar |
| FirstName | varchar |
我现在已经尝试了几个小时,但我似乎无法做到正确。请帮忙!!
答案 0 :(得分:0)
在 SQL-Server 中,您可以执行以下操作:
select case when rn > 1 then '' else [Table] end as [Table],
[column],
[data type]
from(
select [column],
[type],
row_number() over(partition by [Table] order by [Table]) rn
from YourTable
) x
您提供的示例将类似于:
SELECT CASE WHEN rn > 1 THEN '' ELSE [TABLE] END AS [TABLE],
[COLUMN], [DATA type], [Length], [PRECISION], [Scale], [Nullable]
FROM(
SELECT
CAST(t. NAME AS CHAR(12)) AS [TABLE],
CAST(c. NAME AS CHAR(20)) AS [COLUMN], CAST(d. NAME AS CHAR(9)) AS [DATA type],
CASE WHEN d. NAME IN ('char', 'varchar') THEN
STR (c.max_length, 6, 0)
ELSE
''
END AS [Length], CASE
WHEN d. NAME IN ('numeric', 'decimal') THEN
STR (c. PRECISION, 9, 0)
ELSE
''
END AS [PRECISION], CASE
WHEN d. NAME IN ('numeric', 'decimal') THEN
STR (c.scale, 5, 0)
ELSE
''
END AS [Scale], CASE c.is_nullable
WHEN 0 THEN
'not null'
ELSE
''
END AS [Nullable],
ROW_NUMBER() OVER(PARTITION BY CAST(t. NAME AS CHAR(12)) ORDER BY CAST(t. NAME AS CHAR(12))) rn,
[column_id]
FROM
sys. COLUMNS AS c
JOIN sys. TABLES AS t ON c.object_id = t.object_id
JOIN sys.types AS d ON c.system_type_id = d.system_type_id
)x