有2个表:
CREATE TABLE [dbo].[Clients](
[ID] [int] IDENTITY(1,1) NOT NULL,
[FIO] [nvarchar](100) NULL,
[HPhone] [nchar](10) NULL,
[MPhone] [nchar](10) NULL,
CONSTRAINT [PK_Clients] PRIMARY KEY CLUSTERED )
CREATE TABLE [dbo].[Payment](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Paid] [decimal](18, 0) NOT NULL,
[date] [date] NULL,
[IDClient] [int] NULL,
CONSTRAINT [PK_Payment] PRIMARY KEY CLUSTERED
)
如何使sql查询构建此数据:
ID FIO January February March April May etc
--- ------------------ --------- --------- --------- --------- --------- ---------
1 Jimm Salvan 200 200 200 200 NULL etc
2 Bob Dillan 200 200 200 200 NULL etc
答案 0 :(得分:2)
使用PIVOT
表格运算符:
SELECT
Id,
FIO,
[1] AS January,
[2] AS Febrary,
[3] AS March,
[4] AS April,
[5] AS May,
... etc
FROM
(
SELECT
c.id,
c.FIO,
ISNULL(p.paid, 0) AS paid,
MONTH(Date) AS month
FROM clients AS c
LEFT JOIN Payment AS p ON c.Id = p.Id
) AS t
PIVOT
(
SUM(paid)
FOR month IN([1],
[2],
[3],
[4],
[5]
... etc)
) AS p;
修改:您可以使用DATENAME(MONTH, Date)
直接获取月份名称@AndriyM在下面的评论中建议。像这样:
SELECT
*
FROM
(
SELECT
c.id,
c.FIO,
ISNULL(p.paid, 0) AS paid,
DATENAME(month, Date) AS monthname
FROM clients AS c
LEFT JOIN Payment AS p ON c.Id = p.Id
) AS t
PIVOT
(
SUM(paid)
FOR monthname IN(January,
February,
March,
April,
May,
...)
) AS p;