假设我们有一个可以使用以下代码构建的表。
**SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[ACBilling](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Invoice] [int] NULL,
[Product] [varchar](500) NULL,
[Rate] [money] NULL,
[Quantity] [int] NULL,
[Amount] AS ([Rate]*[Quantity]),
[CGSTRate] [money] NULL,
[CGSTAmount] [money] NULL,
[SGSTRate] [money] NULL,
[SGSTAmount] [money] NULL,
[IGSTRate] [money] NULL,
[IGSTAmount] [money] NULL,
[TotalTaxAmount] AS (([CGSTAmount]+[SGSTAmount])+[IGSTAmount])
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO**
我们已将示例数据输入表中,现在我的表看起来像 -
请考虑以下列CGSTRate
,SGSTRate
和IGSTRate
,这些是三种税(百分比可能会有所不同),这些税将是金额列,相关的税值是分别保存在CGSTAmount
,SGSTAmount
和IGSTAmount
列中。
现在,请考虑发票栏,您会看到发票#1包含3条记录,发票#2包含3条记录,发票#3包含3条不同CGSTRate
,SGSTRate
和{{ 1}}和相关的CGSTAmount,SGSTAmount和IGSTRates
。
我想以这样一种方式执行查询:sql应按不同的发票编号,金额列的总和以及IGSTAmount
中的每个税率百分比对记录进行排序,{{1 }和CGSTRate
,它应该添加单独的列以及SGSTRate
,IGSTRate
和CGSTAmount
的SUM,以便我得到以下结果。
有人能帮助我吗?
答案 0 :(得分:0)
可能你正在寻找案件。试试这个 -
SELECT [Invoice],
SUM([Amount]),
SUM(CASE WHEN [CGSTRate] = '6%' THEN [CGSTAmount]) END AS "CGST AMT 6%",
SUM(CASE WHEN [CGSTRate] = '9%' THEN [CGSTAmount]) END AS "CGST AMT 9%",
SUM(CASE WHEN [CGSTRate] = '12%' THEN [CGSTAmount]) END AS "CGST AMT 12%",
SUM(CASE WHEN [SGSTRate] = '6%' THEN [SGSTAmount]) END AS "SGST AMT 6%",
SUM(CASE WHEN [SGSTRate] = '9%' THEN [SGSTAmount]) END AS "SGST AMT 9%",
SUM(CASE WHEN [SGSTRate] = '12%' THEN [SGSTAmount]) END AS "SGST AMT 12%",
SUM(CASE WHEN [IGSTRate] = '12%' THEN [IGSTAmount]) END AS "IGST AMT 12%",
SUM(CASE WHEN [IGSTRate] = '24%' THEN [IGSTAmount]) END AS "IGST AMT 24%",
SUM(CASE WHEN [IGSTRate] = '28%' THEN [IGSTAmount]) END AS "IGST AMT 28%"
FROM [dbo].[ACBilling]
GROUP BY [Invoice];
希望这有帮助。