开发者

SQL..Sum two rows

开发者 https://www.devze.com 2023-03-16 18:03 出处:网络
Sample data: LOCATIONNAMELABEL1LABEL2 SERVICE TIME NYAndrewABHOUSE2555 NYAndrewABCAR35 NJCopleyCAHOUSE1025

Sample data:

LOCATION   NAME   LABEL1   LABEL2 SERVICE TIME
NY         Andrew    A       B      HOUSE  2555
NY         Andrew    A       B      CAR    35
NJ         Copley    C       A      HOUSE  1025
NY         Copley    A       B      HOUSE  650
VA         Dalton    D       C      PET    25

What I want to do is add another column where in it shows sum(Time) of rows with same data except for the Service.Also, the services that I need are only the sum of car and house.Is this possible? If not can you help me with the right query

Sample output I need:

LOCATION   NAME   LABEL1   LABEL2 SERVICE TIME     SUM
NY         Andrew    A       B      HOUSE  2555    **2590**
NY         Andrew    A       B      CAR    35
NJ         Copley    C       A      HOUS开发者_运维问答E  1025    1025
NY         Copley    A       B      HOUSE  650     650


SELECT `LOCATION`, `NAME`, `LABEL1`, `LABEL2`, SUM(`TIME`)
  FROM `myTable`
 WHERE `SERVICE` = "CAR" OR `SERVICE` = "HOUSE"
 GROUP BY `LOCATION`, `NAME`, `LABEL1`, `LABEL2`

This does not add another column, but it does return the data you requested in a resultset when run as a query. I recommend taking this approach.

You should also ensure that your indexes are set up optimally for this sort of query.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号