1

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
4

1 に答える 1

3

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;

SQLフィドルデモ


編集: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;

このような。

于 2013-03-09T17:02:41.713 に答える