我还在学习SQL,我正在使用'pubs'数据库。我正在尝试将一些元素连接到一个新的有序列表。
SELECT t.title_id
,t.title
,DATEDIFF(dd, pubdate, GETDATE()) / 365 AS AantalJaren
,au.au_fname + ' ' + au.au_lname AS authorname
FROM titles t
LEFT JOIN titleauthor ta ON t.title_id = ta.title_id
LEFT JOIN authors au ON ta.au_id = au.au_id
WHERE t.title_id IN (
SELECT title_id
FROM titleauthor
GROUP BY title_id
HAVING COUNT(title_id) > 1
)
ORDER BY t.title_id
很难解释我想要的东西,所以我只会在图片中展示它:
这就是我得到的:
这就是我想要的:
答案 0 :(得分:0)
我认为这就是你要找的东西,
样本表结构:
CREATE TABLE #Yourtable
(
TITLEID VARCHAR(30),
TITLE VARCHAR(100),
AntalJaren INT,
AUTHOR_NAME VARCHAR(30)
)
INSERT INTO #Yourtable VALUES
('BU1032', 'The Busy Executive''s Database Guide', 23, 'Maijorie Green'),
('BU1032', 'The Busy Executive''s Database Guide', 23, 'Abraham Bennet'),
('BU1111', 'Cooking with Computers: Surreptitious Balance Sheets', 23, 'Michael O''Leary'),
('BU1111', 'Cooking with Computers: Surreptitious Balance Sheets', 23, 'Steams Mac Feather'),
('MC3021', 'The Gourmet Microwave', 23, 'Michel DeFrance'),
('MC3021', 'The Gourmet Microwave', 23, 'Anne Ringer'),
('PC8888', 'Sestets of Silicon Valley', 20, 'Ann Dull'),
('PC8888', 'Secrets of Silicon Valley', 20, 'Sheryl Hunter'),
('PS1372', 'Computer Phobic AND Non-Phobic Individuals: Beha..', 23, 'Steams Mac Feather'),
('PS1372', 'Computer Phobic AND Non-Phobic Individuals: Beha..', 23, 'Livia Karsen'),
('PS2091', 'Is Anger the Enemy?', 23, 'Anne Ringer'),
('PS2091', 'Is Anger the Enemy?', 23, 'Albert Ringer'),
('TC7777', 'Sushi. Anyone?', 23, 'Michael O''Leary')
查询:
SELECT *
FROM (SELECT TITLEID,
TITLE,
AntalJaren,
AUTHOR_NAME,
'AUTHOR_'
+ CONVERT(VARCHAR(3), Row_Number() OVER (PARTITION BY TITLEID, TITLE ORDER BY TITLEID)) AS TEMP
FROM #Yourtable)A
PIVOT (Max(AUTHOR_NAME)
FOR TEMP IN ([AUTHOR_1],
[AUTHOR_2]))PV