gpt4 book ai didi

sql - SQL Server:如何合并来自同一表的两个选择查询并在列上获取结果

转载 作者:行者123 更新时间:2023-12-01 16:43:17 25 4
gpt4 key购买 nike

我想在具有分组依据的同一张表上合并两个查询。

这是我的桌子:

 Date#####   |  Value1 |  Value2 |   Value3 | Type
------------------------------------------------------
23/04/2014 | 1,2 | 12,3 | 10 | Green
23/04/2014 | 11,2 | 3 | 10,3 | Non-Green
24/04/2014 | 10,9 | 3 | 11 | Green
24/04/2014 | 2,3 | 12,3 | 8 | Green
24/04/2014 | 10 | 1 | 11 | Non-Green
25/04/2014 | 10 | 2 | 10,8 | Non-Green
25/04/2014 | 1,4 | 5 | 12 | Green


值是 Decimal类型。计算value1,value2,value3> =10。预期结果:

 Date#####   | Green |Non-Green
------------------------------
23/04/2014 | 2 | 2
24/04/2014 | 3 | 2
25/04/2014 | 1 | 2


绿色和非绿色的值来自于对value1,value2,value3的计数> = 10,这是我的第一个查询:

Dim strCommand As String = "SELECT d, LW, cnt FROM(SELECT TOP 7 [date] AS d, [Type] as LW, SUM(CASE WHEN Value1 >= 10 THEN 1 ELSE 0 END + CASE WHEN Value2 >= 10 THEN 1 ELSE 0 END + CASE WHEN Value3 >= 10 THEN 1 ELSE 0 END) AS cnt FROM tbBooth where Type = 'Green' GROUP BY [date],[Type] ORDER BY [date] DESC) x ORDER BY d ASC"


显示:

 Date#####   | Cnt |Type
------------------------
23/04/2014 | 2 | Green
24/04/2014 | 3 | Green
25/04/2014 | 1 | Green


我的第二个查询:

Dim strCommand As String = "SELECT d, LW, cnt FROM(SELECT TOP 7 [date] AS d, [Type] as LW, SUM(CASE WHEN Value1 >= 10 THEN 1 ELSE 0 END + CASE WHEN Value2 >= 10 THEN 1 ELSE 0 END + CASE WHEN Value3 >= 10 THEN 1 ELSE 0 END) AS cnt FROM tbBooth where Type = 'Non-Green' GROUP BY [date],[Type] ORDER BY [date] DESC) x ORDER BY d ASC"


显示:

 Date#####   | Cnt |Type
------------------------
23/04/2014 | 2 | Non-Green
24/04/2014 | 2 | Non-Green
25/04/2014 | 2 | Non-Green


我想将两个查询合并为一个,并获取日期,绿色结果和非绿色结果。假设我有很多日期组,我希望它仅显示基于 ASC顺序的最后7组日期。

反正有怎么做呢?我尝试查看其他SO帖子,例如使用UNION或PIVOT,但是我不知道如何在我的代码中实现它。

抱歉,我昨天已经发布了这个问题,这是编辑后的预期结果...。

提前致谢....

最佳答案

SELECT d, 
sum(CASE WHEN LW = 'Green' THEN cnt ELSE 0 END) [Green],
sum(CASE WHEN LW = 'Non-Green' THEN cnt ELSE 0 END) [Non-Green]
FROM
(
SELECT [date] AS d,
[Type] as LW,
CASE WHEN Value1 >= 10 THEN 1 ELSE 0 END +
CASE WHEN Value2 >= 10 THEN 1 ELSE 0 END +
CASE WHEN Value3 >= 10 THEN 1 ELSE 0 END AS cnt,
DENSE_RANK() over (ORDER BY [date] DESC) dr
FROM tbBooth
WHERE Type in ('Green','Non-Green')
) x
WHERE dr < 8
GROUP BY d
ORDER BY d ASC

关于sql - SQL Server:如何合并来自同一表的两个选择查询并在列上获取结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23355354/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com